-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcombination-sum.js
More file actions
86 lines (77 loc) · 1.8 KB
/
Copy pathcombination-sum.js
File metadata and controls
86 lines (77 loc) · 1.8 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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
/**
* @param {number[]} candidates
* @param {number} target
* @return {number[][]}
*/
// Time O(2^t) where t is the target
// Space O(2^t) where t is the target
var combinationSum = function (candidates, target) {
const uniqueCombinations = [];
combinationHelper(0, [], 0, target, candidates, uniqueCombinations);
return uniqueCombinations;
};
function combinationHelper(
index,
currentCombination,
totalSum,
target,
candidates,
uniqueCombinations
) {
if (totalSum === target) {
uniqueCombinations.push(currentCombination.slice());
return;
}
if (index >= candidates.length || totalSum > target) return;
currentCombination.push(candidates[index]);
combinationHelper(
index,
currentCombination,
totalSum + candidates[index],
target,
candidates,
uniqueCombinations
);
currentCombination.pop();
combinationHelper(
index + 1,
currentCombination,
totalSum,
target,
candidates,
uniqueCombinations
);
}
//////////////////////////////////////////////
// Combination Sum 2
// No duplicates allowed
/**
* @param {number[]} candidates
* @param {number} target
* @return {number[][]}
*/
var combinationSum2 = function (candidates, target) {
candidates.sort((a, b) => a - b);
let paths = [];
find(target, [], 0, candidates, paths);
return paths;
};
// Time O(2^n) | Space O(n)
function find(target, currPath, index, candidates, paths) {
if (target === 0) {
paths.push(currPath.slice());
return;
} else {
while (index < candidates.length && target - candidates[index] >= 0) {
find(
target - candidates[index],
[...currPath, candidates[index]],
index + 1,
candidates,
paths
);
index++;
while (candidates[index - 1] === candidates[index]) index++;
}
}
}