-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathmain.js
More file actions
36 lines (35 loc) · 834 Bytes
/
Copy pathmain.js
File metadata and controls
36 lines (35 loc) · 834 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
/**
* @param {number[]} candidates
* @param {number} target
* @return {number[][]}
*/
var combinationSum = function (candidates, target) {
const ans = []
candidates.sort((x, y) => x - y)
function dfs (res, index, left) {
if (index >= candidates.length || left < 0 || candidates[index] > left) {
return
}
for (let i = index; i < candidates.length; i++) {
const item = candidates[i]
if (item < left) {
res.push(item)
dfs(res, i, left - item)
res.pop()
} else if (item === left) {
res.push(item)
ans.push(res.slice())
res.pop()
} else {
break
}
}
}
dfs([], 0, target)
return ans
}
if (process.env.LZS) {
// local test
console.log(combinationSum([2, 3, 6, 7], 7))
console.log(combinationSum([2, 5], 100))
}