Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 52e38fa

Browse files
combination-sum
1 parent 8cc5105 commit 52e38fa

File tree

2 files changed

+42
-0
lines changed

2 files changed

+42
-0
lines changed

‎src/algorithms/combination-sum.js‎

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
/**
2+
* @param {number[]} candidates
3+
* @param {number} target
4+
* @return {number[][]}
5+
*/
6+
function combinationSum(
7+
candidates,
8+
target,
9+
solution = [],
10+
current = [],
11+
currentSum = 0,
12+
index = 0,
13+
) {
14+
if (currentSum === target) {
15+
solution.push(current);
16+
}
17+
18+
let candidate = candidates[index];
19+
let newSum = currentSum + candidate;
20+
21+
if (newSum <= target) {
22+
combinationSum(candidates, target, solution, current.concat(candidate), newSum, index);
23+
} else if (index < candidates.length - 1) {
24+
const newIndex = index + 1;
25+
while (currentSum + candidates[newIndex] > target) current.pop();
26+
candidate = candidates[newIndex];
27+
newSum = currentSum + candidate;
28+
combinationSum(candidates, target, solution, current.concat(candidate), newSum, newIndex);
29+
}
30+
31+
32+
return solution;
33+
}
34+
35+
module.exports = combinationSum;
Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
const combinationSum = require('./combination-sum.js');
2+
3+
describe('combinationSum', () => {
4+
it('should return empty', () => {
5+
expect(combinationSum([], 0)).toEqual([[]]);
6+
});
7+
});

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /