LeetCode-040-组合总和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]
]

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/combination-sum-ii

解题思路

总体思路和39题一样, 多了两个地方要修改

  1. 避免答案集合中有重复组合, 请看大神评论
image.png
  1. 递归时 begin 传参 i + 1, 因为一个组合中同个元素只允许用一次

代码

class Solution {
    public List<List<Integer>> combinationSum2(int[] candidates, int target) {
        List<List<Integer>> result = new LinkedList<>();
        if (candidates == null || candidates.length == 0) {
            return result;
        }
        Arrays.sort(candidates);
        Deque<Integer> path = new LinkedList<>();
        dfs(candidates, 0, target, result, path);
        return result;
    }

    private void dfs(int[] candidates, int begin, int target, List<List<Integer>> result, Deque<Integer> path) {
        if (target == 0) {
            result.add(new LinkedList<>(path));
        } else {
            for (int i = begin; i < candidates.length; i++) {
                int candidate = candidates[i];
                // 这句是"避免答案集合中有重复组合"的关键
                // 要跳过"同一层级"的重复数字, 但是不能跳过不同层级的同一数字
                // "同一层级"的重复数字特点就是 i != begin && candidates[i - 1] == candidate
                if (i != begin && candidates[i - 1] == candidate) {
                    continue;
                }
                if (target - candidate < 0) {
                    break; // return
                } else {
                    path.addLast(candidate);
                    // 和39题的差异: begin 传参 i + 1, 因为一个组合中同个元素只允许用一次
                    dfs(candidates, i + 1, target - candidate, result, path);
                    path.removeLast();
                }
            }
        }
    }
}
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容