首页 > 编程语言 > 详细

回溯算法:求组合总和(二)

时间:2021-05-17 00:32:07      阅读:28      评论:0      收藏:0      [点我收藏+]

40. 组合总和 II

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

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

说明:

  • 所有数字(包括目标数)都是正整数
  • 解集不能包含重复的组合
输入: candidates = [10,1,2,7,6,1,5], target = 8,
所求解集为:
[
  [1, 7],
  [1, 2, 5],
  [2, 6],
  [1, 1, 6]
]

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

思路

难点在于:集合(数组candidates)有重复元素,但还不能有重复的组合。

可以把所有组合求出来,再用set或者map去重,但这么做很容易超时,所以要在搜索的过程中就去掉重复组合。

在题目中,元素在同一个组合内是可以重复的,但两个组合不能相同。所以我们要去重的是同一树层上的“使用过”,同一树枝上的都是一个组合里的元素,不用去重。
技术分享图片

代码

class Solution {
    List<Integer> temp = new ArrayList<Integer>();
    List<List<Integer>> ans = new ArrayList<List<Integer>>();

    public List<List<Integer>> combinationSum2(int[] candidates, int target) {
        boolean[] used = new boolean[candidates.length];
        Arrays.sort(candidates);
        backtracking(candidates,target,0,0,used);
        return ans;
    }
    private void backtracking(int[] candidates, int target,int sum,int begin,boolean[] used) {
        if (sum == target) {
            ans.add(new ArrayList<>(temp));
            return;
        }

        // 遍历可能的搜索起点
        for (int i=begin;i<candidates.length && sum + candidates[i] <= target;i++) {
            if (i > 0 && candidates[i] == candidates[i - 1] && used[i - 1] == false) {
                continue;
            }
            temp.add(candidates[i]);
            used[i] = true;
            // 下一轮搜索
            backtracking(candidates, target,sum+candidates[i],i+1,used);
            used[i] = false;
            // 回头的过程
            temp.remove(temp.size() - 1);
        }
    }
}

回溯算法:求组合总和(二)

原文:https://www.cnblogs.com/luedong/p/14774510.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!