Skip to content

Commit d034dd0

Browse files
committed
feat: add Combination Sum II
1 parent dd003b1 commit d034dd0

File tree

2 files changed

+34
-0
lines changed

2 files changed

+34
-0
lines changed

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -75,6 +75,7 @@ Roadmap: https://neetcode.io/roadmap
7575
| 78 | [Subsets](https://leetcode.com/problems/subsets/description/) | Medium | [ts](./TypeScript/78.subsets.ts) | Backtracking |
7676
| 39 | [Combination Sum](https://leetcode.com/problems/combination-sum/description/) | Medium | [ts](./TypeScript/39.combination-sum.ts) | Backtracking |
7777
| 90 | [Subsets II](https://leetcode.com/problems/subsets-ii/description/) | Medium | [ts](./TypeScript/90.subsets-ii.ts) | Backtracking |
78+
| 40 | [Combination Sum II](https://leetcode.com/problems/combination-sum-ii/description/) | Medium | [ts](./TypeScript/40.combination-sum-ii.ts) | Backtracking |
7879

7980
### Others
8081

TypeScript/40.combination-sum-ii.ts

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
function combinationSum2(candidates: number[], target: number): number[][] {
2+
const combinations: number[][] = [];
3+
4+
function backtrace(index: number, combination: number[], target: number) {
5+
if (target === 0) {
6+
combinations.push(combination.slice());
7+
return;
8+
}
9+
10+
if (target < 0) {
11+
return;
12+
}
13+
14+
let prev = -1;
15+
for (let i = index; i < candidates.length; i++) {
16+
if (candidates[i] === prev) {
17+
continue;
18+
}
19+
20+
combination.push(candidates[i]);
21+
backtrace(i + 1, combination, target - candidates[i]);
22+
prev = candidates[i];
23+
combination.pop();
24+
}
25+
}
26+
27+
candidates.sort();
28+
backtrace(0, [], target);
29+
30+
return combinations;
31+
}
32+
33+
console.log(combinationSum2([10, 1, 2, 7, 6, 1, 5], 8));

0 commit comments

Comments
 (0)