Skip to content

Commit f2c66d2

Browse files
author
Tushar Borole
committed
40. Combination Sum II
1 parent a8041db commit f2c66d2

File tree

3 files changed

+125
-36
lines changed

3 files changed

+125
-36
lines changed

.idea/workspace.xml

Lines changed: 78 additions & 36 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -63,6 +63,7 @@
6363
| 540 | [Single Element in a Sorted Array](https://leetcode.com/problems/single-element-in-a-sorted-array/) | [single_element_in_a_sorted_array.js](single_element_in_a_sorted_array.js) | 60 ms | 35.2 MB | Medium |
6464
| 347 | [Top K Frequent Elements](https://leetcode.com/problems/top-k-frequent-elements/) | [top_k_frequent_elements.js](top_k_frequent_elements.js) | 80 ms | 39.1 MB | Medium |
6565
| 39 | [Combination Sum](https://leetcode.com/problems/combination-sum/) | [combination_sum.js](combination_sum.js) | 72 ms | 35.8 MB | Medium |
66+
| 40 | [Combination Sum II](https://leetcode.com/problems/combination-sum-ii/) | | 84 ms | 37.6 MB | Medium |
6667

6768

6869
## Others

combination_sum_II.js

Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
/**
2+
* @param {number[]} candidates
3+
* @param {number} target
4+
* @return {number[][]}
5+
*/
6+
var combinationSum2 = function(
7+
candidates,
8+
target,
9+
index = 0,
10+
curr = [],
11+
combinations = [],
12+
store = {}
13+
) {
14+
if (target <= 0) {
15+
if (target === 0) {
16+
let val = curr.slice(0);
17+
let sortedVal = val
18+
.slice(0)
19+
.sort()
20+
.join("");
21+
if (!store.hasOwnProperty(sortedVal)) {
22+
store[sortedVal] = true;
23+
combinations.push(val);
24+
}
25+
}
26+
return;
27+
}
28+
if (index < candidates.length) {
29+
let current = candidates[index];
30+
curr.push(current);
31+
combinationSum2(
32+
candidates,
33+
target - current,
34+
index + 1,
35+
curr,
36+
combinations,
37+
store
38+
);
39+
curr.pop();
40+
combinationSum2(candidates, target, index + 1, curr, combinations, store);
41+
}
42+
43+
return combinations;
44+
};
45+
46+
combinationSum2([10, 1, 2, 7, 6, 1, 5], 8); //?

0 commit comments

Comments
 (0)