-
Notifications
You must be signed in to change notification settings - Fork 41
/
solution.ts
40 lines (38 loc) · 1.03 KB
/
solution.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
function combinationSum2 (candidates: number[], target: number): number[][] {
candidates.sort((a, b) => a - b);
const result:number[][] = [];
backTracking(
candidates,
0,
target,
new Array(candidates.length).fill(false),
[] as number[],
result
);
return result;
}
function backTracking (candidates:number[], index:number, rest:number, used:boolean[], sequence:number[], result:number[][]) {
if (rest === 0) {
result.push(sequence.slice());
return;
}
if (rest < 0 || index === candidates.length) {
return;
}
backTracking(
candidates,
index + 1,
rest,
used,
sequence,
result
);
if (index > 0 && candidates[index] === candidates[index - 1] && !used[index - 1]) {
return;
}
sequence.push(candidates[index]);
used[index] = true;
backTracking(candidates, index + 1, rest - candidates[index], used, sequence, result);
used[index] = false;
sequence.pop();
}