mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-08 16:54:50 +08:00
update: 0040.组合总和II JS版本增加使用used去重
This commit is contained in:
@ -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
|
||||||
|
|
||||||
```c
|
```c
|
||||||
|
Reference in New Issue
Block a user