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 bc491d5

Browse files
work with 2 numbers
1 parent 52e38fa commit bc491d5

File tree

2 files changed

+30
-4
lines changed

2 files changed

+30
-4
lines changed

‎src/algorithms/combination-sum.js‎

Lines changed: 11 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -17,15 +17,22 @@ function combinationSum(
1717

1818
let candidate = candidates[index];
1919
let newSum = currentSum + candidate;
20+
let newCurrent = current.concat(candidate);
2021

2122
if (newSum <= target) {
22-
combinationSum(candidates, target, solution, current.concat(candidate), newSum, index);
23+
combinationSum(candidates, target, solution, newCurrent, newSum, index);
2324
} else if (index < candidates.length - 1) {
2425
const newIndex = index + 1;
25-
while (currentSum + candidates[newIndex] > target) current.pop();
2626
candidate = candidates[newIndex];
27-
newSum = currentSum + candidate;
28-
combinationSum(candidates, target, solution, current.concat(candidate), newSum, newIndex);
27+
newSum = currentSum;
28+
const reducedCurrent = current.slice(); // clone current
29+
while (newSum + candidate > target) {
30+
const deletedCandidate = reducedCurrent.pop();
31+
newSum -= deletedCandidate;
32+
}
33+
newSum += candidate;
34+
newCurrent = reducedCurrent.concat(candidate);
35+
combinationSum(candidates, target, solution, newCurrent, newSum, newIndex);
2936
}
3037

3138

‎src/algorithms/combination-sum.spec.js‎

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,4 +4,23 @@ describe('combinationSum', () => {
44
it('should return empty', () => {
55
expect(combinationSum([], 0)).toEqual([[]]);
66
});
7+
8+
it('should find solution for one item', () => {
9+
expect(combinationSum([1], 1)).toEqual([[1]]);
10+
});
11+
12+
it('should use multiple times one value', () => {
13+
expect(combinationSum([1], 2)).toEqual([[1, 1]]);
14+
});
15+
16+
it('should not find solution', () => {
17+
expect(combinationSum([2], 1)).toEqual([]);
18+
});
19+
20+
fit('should not find solution', () => {
21+
expect(combinationSum([1, 2], 3)).toEqual([
22+
[1, 1, 1],
23+
[1, 2],
24+
]);
25+
});
726
});

0 commit comments

Comments
(0)

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