Skip to content

Commit 2423176

Browse files
committed
feat: add question 40
1 parent 09802a6 commit 2423176

File tree

1 file changed

+43
-0
lines changed

1 file changed

+43
-0
lines changed

40.组合总和-ii.js

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
/*
2+
* @lc app=leetcode.cn id=40 lang=javascript
3+
*
4+
* [40] 组合总和 II
5+
*
6+
* 1. 与39题类似, 在去除重复结果上有些不同, 在每轮遍历中, 相同的数字只用一次, 在不同轮遍历中, 可以用相同数字
7+
*/
8+
9+
// @lc code=start
10+
/**
11+
* @param {number[]} candidates
12+
* @param {number} target
13+
* @return {number[][]}
14+
*/
15+
var combinationSum2 = function(candidates, target) {
16+
candidates.sort((a, b) => a - b);
17+
const result = [];
18+
const path = [];
19+
20+
function dfs(target, start) {
21+
if (target === 0) {
22+
result.push([...path]);
23+
} else if (target > 0) {
24+
for (let i = start; i < candidates.length; i++) {
25+
if (target < candidates[i]) {
26+
break;
27+
}
28+
if (candidates[i] !== candidates[i - 1]) {
29+
const t = candidates[i];
30+
path.push(t);
31+
candidates.splice(i, 1);
32+
dfs(target - t, i);
33+
candidates.splice(i, 0, t);
34+
path.pop();
35+
}
36+
}
37+
}
38+
}
39+
dfs(target, 0);
40+
41+
return result;
42+
};
43+
// @lc code=end

0 commit comments

Comments
 (0)