Skip to content

Commit 213d3ac

Browse files
committedJan 15, 2022
Add solution #40
1 parent 264b661 commit 213d3ac

File tree

2 files changed

+38
-0
lines changed

2 files changed

+38
-0
lines changed
 

‎README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -40,6 +40,7 @@
4040
35|[Search Insert Position](./0035-search-insert-position.js)|Easy|
4141
36|[Valid Sudoku](./0036-valid-sudoku.js)|Medium|
4242
39|[Combination Sum](./0039-combination-sum.js)|Medium|
43+
40|[Combination Sum II](./0040-combination-sum-ii.js)|Medium|
4344
41|[First Missing Positive](./0041-first-missing-positive.js)|Hard|
4445
42|[Trapping Rain Water](./0042-trapping-rain-water.js)|Hard|
4546
43|[Multiply Strings](./0043-multiply-strings.js)|Medium|

‎solutions/0040-combination-sum-ii.js

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
/**
2+
* 40. Combination Sum II
3+
* https://leetcode.com/problems/combination-sum-ii/
4+
* Difficulty: Medium
5+
*
6+
* Given a collection of candidate numbers (candidates) and a target number (target),
7+
* find all unique combinations in candidates where the candidate numbers sum to target.
8+
*
9+
* Each number in candidates may only be used once in the combination.
10+
*
11+
* Note: The solution set must not contain duplicate combinations.
12+
*/
13+
14+
/**
15+
* @param {number[]} candidates
16+
* @param {number} target
17+
* @return {number[][]}
18+
*/
19+
var combinationSum2 = function(candidates, target) {
20+
const result = [];
21+
candidates.sort((a, b) => a - b);
22+
backtrack(result, candidates, target);
23+
return result;
24+
};
25+
26+
function backtrack(result, candidates, target, combination = [], offset = 0) {
27+
if (target < 0) {
28+
return;
29+
} else if (target === 0) {
30+
result.push(combination);
31+
} else {
32+
for (let i = offset; i < candidates.length; i++) {
33+
if (i > offset && candidates[i] === candidates[i - 1]) continue;
34+
backtrack(result, candidates, target - candidates[i], [...combination, candidates[i]], i + 1);
35+
}
36+
}
37+
}

0 commit comments

Comments
 (0)
Please sign in to comment.