-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path39-combination-sum.js
More file actions
47 lines (38 loc) · 953 Bytes
/
Copy path39-combination-sum.js
File metadata and controls
47 lines (38 loc) · 953 Bytes
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
/**
* @param {number[]} candidates
* @param {number} target
* @return {number[][]}
*/
var combinationSum = function(candidates, target) {
const result = [], combination = [];
const dfs = (i) => {
if (target < 0 || i >= candidates.length) return;
if (target == 0) {
result.push([...combination]);
return;
}
const num = candidates[i];
combination.push(num);
target -= num;
dfs(i);
combination.pop();
target += num;
dfs(i + 1);
}
dfs(0);
return result;
};
const data = [
{
candidates: [2,3,6,7],
target: 7,
output: [[2,2,3],[7]]
},
];
for (let d of data) {
console.log(JSON.stringify(d));
const result = combinationSum(d.candidates, d.target);
console.log('result = ', JSON.stringify(result));
(JSON.stringify(result) === JSON.stringify(d.output)) ? console.log('ok') : console.error('nok');
console.log('----------');
}