Merge pull request #933 from Tiffany-yuan/master
update: 0040.组合总和II JS版本增加使用used去重
This commit is contained in:
commit
7199a4c82e
|
|
@ -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
|
||||||
|
|
|
||||||
Loading…
Reference in New Issue