Merge pull request #933 from Tiffany-yuan/master

update: 0040.组合总和II JS版本增加使用used去重
This commit is contained in:
程序员Carl
2021-12-08 10:20:45 +08:00
committed by GitHub

View File

@ -457,6 +457,37 @@ var combinationSum2 = function(candidates, target) {
}
};
```
**使用used去重**
```js
var combinationSum2 = function(candidates, target) {
let res = [];
let path = [];
let total = 0;
const len = candidates.length;
candidates.sort((a, b) => a - b);
let used = new Array(len).fill(false);
const backtracking = (startIndex) => {
if (total === target) {
res.push([...path]);
return;
}
for(let i = startIndex; i < len && total < target; i++) {
const cur = candidates[i];
if (cur > target - total || (i > 0 && cur === candidates[i - 1] && !used[i - 1])) continue;
path.push(cur);
total += cur;
used[i] = true;
backtracking(i + 1);
path.pop();
total -= cur;
used[i] = false;
}
}
backtracking(0);
return res;
};
```
## C
```c