# 【进阶篇 - Day 50】 2020-12-20 - 40. 组合总和 II(05. 剪枝)

# 题目描述

# 入选理由

1.上一题的进阶版,如果会了上一题,稍微拓展一下你会么?

# 题目描述

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

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

说明:

所有数字(包括目标数)都是正整数。 解集不能包含重复的组合。 示例 1:

输入: candidates = [10,1,2,7,6,1,5], target = 8, 所求解集为: [ [1, 7], [1, 2, 5], [2, 6], [1, 1, 6] ] 示例 2:

输入: candidates = [2,5,2,1,2], target = 5, 所求解集为: [ [1,2,2], [5] ]

来源:力扣(LeetCode) 链接:leetcode-cn.com/problems/combination-sum-ii 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

# 我的回答

https://github.com/leetcode-pp/91alg-2/issues/80#issuecomment-748736782

# 解法一

# 时空复杂度

时间复杂度:O(n*logn)

空间复杂度: O(n)

对比组合 1 只需要回溯递归时不选取自己

这样还会出现,[1,7] 和 [7,1] 这种重复现象 ,所以对他进行排序后,就会出现[1,2,2,2,2,2,7] 这种情况,当还没到 target 的时候,对相邻的相同值进行跳过即可去重

var combinationSum2 = function (candidates, target) {
    const res = []
    candidates = candidates.sort((a, b) => a - b)
    function dfs(index, temp = [], sum = 0) {

        if (sum === target) {
            res.push([...temp])
            return
        }
        if (sum > target) return
        for (let i = index; i < candidates.length; i++) {
            if (candidates[i] > target) continue
            if (i - 1 >= index && candidates[i - 1] === candidates[i]) continue
            temp.push(candidates[i])
            dfs(i + 1, temp, sum + candidates[i])
            temp.pop()
        }
    }
    dfs(0)
    return res
};

# 参考回答

Last Updated: 12/22/2022, 9:53:26 AM