Skip to content

Commit

Permalink
Merge pull request #5374 from alexgarcia1907/retos/reto#38/javascript
Browse files Browse the repository at this point in the history
Reto #38 - javascript
  • Loading branch information
Roswell468 authored Oct 16, 2023
2 parents 7e7f57e + 7b27526 commit f5ab30f
Showing 1 changed file with 31 additions and 0 deletions.
31 changes: 31 additions & 0 deletions Retos/Reto #38 - LAS SUMAS [Media]/javascript/alexgarcia1907.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
function find_sums(numbers, target) {
// Sort numbers and filter in case we have negative numbers
let sortedAndFilteredNumbers = numbers.sort().filter((number) => {
return number > 0
})
if (sortedAndFilteredNumbers.length === 0) return []

function find_sum(start, target, combination) {
// find solution
if (target === 0) {
result.push([...combination])
}

// backtracking
for (let i = start; i < sortedAndFilteredNumbers.length; i++) {
if (i > start && sortedAndFilteredNumbers[i] === sortedAndFilteredNumbers[i - 1]) {
continue
}

combination.push(sortedAndFilteredNumbers[i]);
find_sum(i + 1, target - sortedAndFilteredNumbers[i], combination);
combination.pop();
}
}

let result = []
find_sum(0, target, [])
return result
}

console.log(find_sums([1, 5, 2, 2, 1, 1], 6))

0 comments on commit f5ab30f

Please sign in to comment.