leetcode *40. 组合总和 II

【题目】*40. 组合总和 II

给定一个数组 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]
]

【解题思路1】回溯剪枝

例如 [1, 2, 2, 5, ……]
1, 2, 2, 5……是允许的
但是两个path分别选了两个不同的2组成了同样的1, 2, 5……是不允许的

用 if (i > begin && candidates[i] == candidates[i - 1]) 这一句来剪枝并保留需要的答案
可以让同一层级递归,不出现相同的元素。即
                  1
                 / \
                2   2  这种情况不会发生 但是却允许了不同层级之间的重复即:
               /     \
              5       5
                例2
                  1
                 /
                2      这种情况确是允许的
               /
              2  

candidates[i] == candidates[i - 1]判定当前元素是否和之前元素相同的语句。这个语句就能砍掉例1,即不会选择和之前元素相同的元素再次进入递归,就不会出现同层级有一样的元素的情况了。
问题来了,如果把所有当前与之前一个元素相同的都砍掉,那么例2的情况也会消失,我们需要保留例2这种情况,这时可以用 i > begin 来避免这种情况
在一个for循环中,所有被遍历到的数都是属于一个层级的。同一层级中,不选重复的数字,所以当这两个条件都满足的时候i > begin && candidates[i] == candidates[i - 1],就过掉这个重复的数字,但是不影响下一层递归里选这个重复的数字,因为到了下一层递归的时候i==begin

class Solution {
    
    
    public List<List<Integer>> combinationSum2(int[] candidates, int target) {
    
    
        int len = candidates.length;
        List<List<Integer>> res = new ArrayList<>();
        if (len == 0) {
    
    
            return res;
        }

        // 剪枝前提是数组有序
        Arrays.sort(candidates);

        Deque<Integer> path = new ArrayDeque<>(len);
        dfs(candidates, len, 0, target, path, res);
        return res;
    }

    private void dfs(int[] candidates, int len, int begin, int target, Deque<Integer> path, List<List<Integer>> res) {
    
    
        if (target == 0) {
    
    
            res.add(new ArrayList<>(path));
            return;
        }
        for (int i = begin; i < len; i++) {
    
    
            // 大剪枝
            if (target - candidates[i] < 0) {
    
    
                break;
            }

            // 小剪枝,重复的数不进行递归,但是在同一个path里可以出现重复的数
            if (i > begin && candidates[i] == candidates[i - 1]) {
    
    
                continue;
            }

            path.addLast(candidates[i]);

            // 因为元素不可以重复使用,这里递归传递下去的是 i + 1 而不是 i
            dfs(candidates, len, i + 1, target - candidates[i], path, res);

            path.removeLast();
        }
    }
}

猜你喜欢

转载自blog.csdn.net/XunCiy/article/details/108507583
今日推荐