Skip to content

Commit c60f537

Browse files
committed
solve: combination sum
1 parent aba1f66 commit c60f537

File tree

1 file changed

+24
-0
lines changed

1 file changed

+24
-0
lines changed

combination-sum/tolluset.ts

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
/**
2+
* TC: O(candidates.length ^ target / min(candidates))
3+
* SC: O(target / min(candidates)
4+
*/
5+
function combinationSum(candidates: number[], target: number): number[][] {
6+
const result: number[][] = [];
7+
const dfs = (start: number, spot: number, path: number[]) => {
8+
if (spot === 0) {
9+
result.push([...path]);
10+
return;
11+
}
12+
13+
for (let i = start; i < candidates.length; i++) {
14+
if (candidates[i] <= spot) {
15+
path.push(candidates[i]);
16+
dfs(i, spot - candidates[i], path);
17+
path.pop();
18+
}
19+
}
20+
};
21+
dfs(0, target, []);
22+
23+
return result;
24+
}

0 commit comments

Comments
 (0)