Skip to content

Commit

Permalink
Merge pull request #1035 from Koddi-Evangelista/main
Browse files Browse the repository at this point in the history
feat: add combination sum algorithm using javascript
  • Loading branch information
noisefilter19 committed Oct 6, 2021
2 parents 3047a06 + b99206b commit 8c867e8
Showing 1 changed file with 30 additions and 0 deletions.
30 changes: 30 additions & 0 deletions Javascript/Combination_Sum.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
// problem link: https://leetcode.com/problems/combination-sum/

// Runtime: 136 ms, faster than 28.96% of JavaScript online submissions for Combination Sum.

const combinationSum = (candidates, target) => {
candidates.sort((a, b) => a - b)
return helper(candidates, target)
}
const helper = (
candidates,
target,
start = 0,
sum = 0,
selected = [],
output = []
) => {
if (sum >= target) {
if (sum === target) {
output.push([...selected])
}
return output
}
for (let i = start; i < candidates.length; i++) {
if (sum + candidates[i] > target) break
selected.push(candidates[i])
helper(candidates, target, i, sum + candidates[i], selected, output)
selected.pop()
}
return output
}

0 comments on commit 8c867e8

Please sign in to comment.