算法列表

40. 组合总和 II 中等

布莱克2026-03-08 21:43回溯

问题:

给定一个候选人编号的集合 candidates 和一个目标数 target ,找出 candidates 中所有可以使数字和为 target 的组合。

candidates 中的每个数字在每个组合中只能使用 一次

注意:解集不能包含重复的组合。

示例 1:

[10,1,2,7,6,1,5]8

示例 2:

输入: candidates = [2,5,2,1,2], target = 5,
输出:
[
[1,2,2],
[5]
]

回答:

function combinationSum2(candidates, target) {
    candidates = candidates.sort((a, b) => a - b);
    let res = [];
    let path = [];
    var backTrack = function(index, remain) {
        if (remain == 0) {
            res.push([...path]);
        }
        for (let i = index; i < candidates.length; i++) {
            //同一层递归不可以重复
            if (i > index && candidates[i] == candidates[i - 1]) {
                continue;
            }
            if (candidates[i] > remain) {
                break;
            }
            path.push(candidates[i]);
            backTrack(i + 1, remain - candidates[i]);
            path.pop();
        }
    }
    backTrack(0, target)
    return res;
}


assistant