mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-08 16:54:50 +08:00
@ -508,22 +508,27 @@ func backtracking(startIndex,sum,target int,candidates,trcak []int,res *[][]int)
|
||||
*/
|
||||
var combinationSum2 = function(candidates, target) {
|
||||
const res = []; path = [], len = candidates.length;
|
||||
candidates.sort();
|
||||
candidates.sort((a,b)=>a-b);
|
||||
backtracking(0, 0);
|
||||
return res;
|
||||
function backtracking(sum, i) {
|
||||
if (sum > target) return;
|
||||
if (sum === target) {
|
||||
res.push(Array.from(path));
|
||||
return;
|
||||
}
|
||||
let f = -1;
|
||||
for(let j = i; j < len; j++) {
|
||||
const n = candidates[j];
|
||||
if(n > target - sum || n === f) continue;
|
||||
if(j > i && candidates[j] === candidates[j-1]){
|
||||
//若当前元素和前一个元素相等
|
||||
//则本次循环结束,防止出现重复组合
|
||||
continue;
|
||||
}
|
||||
//如果当前元素值大于目标值-总和的值
|
||||
//由于数组已排序,那么该元素之后的元素必定不满足条件
|
||||
//直接终止当前层的递归
|
||||
if(n > target - sum) break;
|
||||
path.push(n);
|
||||
sum += n;
|
||||
f = n;
|
||||
backtracking(sum, j + 1);
|
||||
path.pop();
|
||||
sum -= n;
|
||||
|
Reference in New Issue
Block a user