Skip to content

Commit a4ce226

Browse files
committed
Time: 4 ms (44.25%), Space: 60 MB (48.05%) - LeetHub
source:ea790c117a2dd3e9dad839ca11d6aa873c31caff
1 parent f2ffb4a commit a4ce226

File tree

1 file changed

+29
-0
lines changed

1 file changed

+29
-0
lines changed
Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
/**
2+
* @param {number[]} candidates
3+
* @param {number} target
4+
* @return {number[][]}
5+
*/
6+
var combinationSum = function(candidates, target) {
7+
const ans = [];
8+
candidates.sort((a, b) => a - b);
9+
10+
function dfs(idx, sum, arr) {
11+
if (sum === target) {
12+
ans.push([...arr]);
13+
return;
14+
}
15+
16+
if (sum > target || idx >= candidates.length) {
17+
return;
18+
}
19+
20+
arr.push(candidates[idx]);
21+
dfs(idx, sum + candidates[idx], arr);
22+
23+
arr.pop();
24+
dfs(idx + 1, sum, arr);
25+
}
26+
27+
dfs(0, 0, []);
28+
return ans;
29+
};

0 commit comments

Comments
 (0)