-
Notifications
You must be signed in to change notification settings - Fork 0
/
combinationSum.ts
48 lines (38 loc) · 1.06 KB
/
combinationSum.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
// <Recursion, Backtracking>
// Time: O(n * 2^n)
// Space: O(m)
// n for the length of candidates
// m for the target (constraints: candidates[i] is positive integer)
// 1. backtracking
function backtrack(
candidates: number[],
target: number,
combinations: number[][],
combination: number[],
index: number,
) {
if (target === 0) {
combinations.push(combination.slice())
return
}
for (let i = index; i < candidates.length; ++i) {
const candidate = candidates[i]
if (target < candidate) {
break
}
combination.push(candidate)
backtrack(candidates, target - candidate, combinations, combination, i)
combination.pop()
}
}
function combinationSum(candidates: number[], target: number): number[][] {
// edge cases
if (!candidates.length) {
return []
}
const combinations: number[][] = []
candidates.sort((a, b) => a - b)
backtrack(candidates, target, combinations, [], 0)
return combinations
}
export { combinationSum }