8000 combination-sum-ii · malipramod/leetcode-js@67beae6 · GitHub
[go: up one dir, main page]

Skip to content

Commit 67beae6

Browse files
committed
combination-sum-ii
1 parent df6d964 commit 67beae6

File tree

2 files changed

+77
-0
lines changed

2 files changed

+77
-0
lines changed
Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
/**
2+
* @param {number[]} candidates
3+
* @param {number} target
4+
* @return {number[][]}
5+
*/
6+
var combinationSum2 = function (candidates, target) {
7+
candidates.sort((a, b) => a - b);
8+
9+
let result = [];
10+
let tempResult = [];
11+
search(0, target);
12+
return result;
13+
14+
function search(current, leftoverTarget) {
15+
if (leftoverTarget === 0 && current === candidates.length)
16+
return result.push(tempResult.slice());
17+
18+
if (leftoverTarget < 0 || current === candidates.length) return;
19+
20+
tempResult.push(candidates[current]);
21+
22+
search(current + 1, leftoverTarget - candidates[current]);
23+
tempResult.pop();
24+
if (tempResult[tempResult.length - 1] !== candidates[current])
25+
search(current + 1, leftoverTarget);
26+
}
27+
};
28+
29+
console.log(combinationSum2([10, 1, 2, 7, 6, 1, 5], 8))
30+
console.log(combinationSum2([2, 5, 2, 1, 2], 5))
Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
# Combination Sum II
2+
3+
Given a collection of candidate numbers (candidates) and a target number (target), find all unique combinations in candidates where the candidate numbers sums to target.
4+
5+
Each number in candidates may only be used once in the combination.
6+
7+
Note:
8+
9+
All numbers (including target) will be positive integers.
10+
11+
The solution set must not contain duplicate combinations.
12+
13+
## Example 1
14+
15+
Input: candidates = [10,1,2,7,6,1,5], target = 8,
16+
17+
A solution set is:
18+
19+
[
20+
21+
[1, 7],
22+
23+
[1, 2, 5],
24+
25+
[2, 6],
26+
27+
[1, 1, 6]
28+
29+
]
30+
31+
## Example 2
32+
33+
Input: candidates = [2,5,2,1,2], target = 5,
34+
35+
A solution set is:
36+
37+
[
38+
39+
[1,2,2],
40+
41+
[5]
42+
43+
]
44+
45+
## More Info
46+
47+
<https://leetcode.com/problems/combination-sum-ii/>

0 commit comments

Comments
 (0)
0