Skip to content

Commit 9538ae3

Browse files
committed
feat: add Combination Sumsubsets
1 parent 52b10d6 commit 9538ae3

File tree

2 files changed

+27
-0
lines changed

2 files changed

+27
-0
lines changed

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -73,6 +73,7 @@ Roadmap: https://neetcode.io/roadmap
7373
| 105 | [Construct Binary Tree from Preorder and Inorder Traversal](https://leetcode.com/problems/construct-binary-tree-from-preorder-and-inorder-traversal/description/) | Medium | [ts](./TypeScript/105.construct-binary-tree-from-preorder-and-inorder-traversal.ts) | Trees |
7474
| 46 | [Permutations](https://leetcode.com/problems/permutations/) | Medium | [ts](./TypeScript/46.permutations.ts) | Backtracking |
7575
| 78 | [Subsets](https://leetcode.com/problems/subsets/description/) | Medium | [ts](./TypeScript/78.subsets.ts) | Backtracking |
76+
| 39 | [Combination Sum](https://leetcode.com/problems/combination-sum/description/) | Medium | [ts](./TypeScript/39.combination-sum.ts) | Backtracking |
7677

7778
### Others
7879

TypeScript/39.combination-sum.ts

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
function combinationSum(candidates: number[], target: number): number[][] {
2+
const combinations = [];
3+
4+
function dfs(i, combination, total) {
5+
if (total === target) {
6+
combinations.push(combination.slice());
7+
return;
8+
}
9+
10+
if (i >= candidates.length || total > target) {
11+
return;
12+
}
13+
14+
combination.push(candidates[i]);
15+
dfs(i, combination, total + candidates[i]);
16+
17+
combination.pop();
18+
dfs(i + 1, combination, total);
19+
}
20+
21+
dfs(0, [], 0);
22+
23+
return combinations;
24+
}
25+
26+
console.log(combinationSum([2, 3, 6, 7], 7));

0 commit comments

Comments
 (0)