Skip to content

Commit 7aa73ea

Browse files
committed
Added combinationSum solution
1 parent f0f8b4d commit 7aa73ea

File tree

1 file changed

+26
-0
lines changed

1 file changed

+26
-0
lines changed

combination-sum/nhistory.js

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
var combinationSum = function (candidates, target) {
2+
let output = [];
3+
4+
// Helper function for depth-first search
5+
const dfs = (index, currentVal, arr) => {
6+
// If the remaining value is less than 0, no need to proceed further
7+
if (currentVal < 0) return;
8+
// If we have found a valid combination
9+
if (currentVal === 0) {
10+
output.push([...arr]);
11+
return;
12+
}
13+
14+
// Iterate over the candidates starting from the current index
15+
for (let i = index; i < candidates.length; i++) {
16+
arr.push(candidates[i]);
17+
dfs(i, currentVal - candidates[i], arr);
18+
arr.pop(); // backtrack
19+
}
20+
};
21+
22+
// Start DFS with the initial target and empty combination
23+
dfs(0, target, []);
24+
25+
return output;
26+
};

0 commit comments

Comments
 (0)