-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcombination-sum.js
More file actions
55 lines (45 loc) · 1.4 KB
/
combination-sum.js
File metadata and controls
55 lines (45 loc) · 1.4 KB
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
48
49
50
51
52
53
54
55
/**
* Problem: Combination Sum
* Link: https://leetcode.com/problems/combination-sum/
* Difficulty: Medium
*
* Find all unique combinations where candidate numbers sum to target.
* Same number may be used unlimited times.
*
* Example: candidates = [2,3,6,7], target = 7 => [[2,2,3],[7]]
*
* Time Complexity: O(n^(target/min))
* Space Complexity: O(target/min)
*/
// JavaScript Solution - Backtracking
function combinationSum(candidates, target) {
const result = [];
function backtrack(start, remaining, current) {
if (remaining === 0) { result.push([...current]); return; }
if (remaining < 0) return;
for (let i = start; i < candidates.length; i++) {
current.push(candidates[i]);
backtrack(i, remaining - candidates[i], current); // i (not i+1) — reuse allowed
current.pop();
}
}
backtrack(0, target, []);
return result;
}
module.exports = combinationSum;
/* Python Solution:
def combinationSum(candidates, target):
result = []
def backtrack(start, remaining, current):
if remaining == 0:
result.append(list(current))
return
if remaining < 0:
return
for i in range(start, len(candidates)):
current.append(candidates[i])
backtrack(i, remaining - candidates[i], current) # same i: reuse allowed
current.pop()
backtrack(0, target, [])
return result
*/