力扣39 组合总和

题目:

给你一个 无重复元素 的整数数组 candidates 和一个目标整数 target ,找出 candidates 中可以使数字和为目标数 target 的 所有 不同组合 ,并以列表形式返回。你可以按 任意顺序 返回这些组合。
candidates 中的 同一个 数字可以 无限制重复被选取 。如果至少一个数字的被选数量不同,则两种组合是不同的。 
对于给定的输入,保证和为 target 的不同组合数少于 150 个。

示例:

输入:candidates = [2,3,6,7], target = 7
输出:[[2,2,3],[7]]
解释:
23 可以形成一组候选,2 + 2 + 3 = 7 。注意 2 可以使用多次。
7 也是一个候选, 7 = 7 。
仅有这两种组合。

思路:

  题目特殊的一点就是同一个数字可以无限制重复被选取,这一点就意味着首先终止条件不能是path.length==深度。

  在这一点上,我陷入了一个误区,就是我一直在想怎么样去避免(如果至少一个数字的被选数量不同,则两种组合是不同的)被选数量相同的情况,以上图取5这条路径为例,其实只要在startIndex选择当前i,那么下次candidates[i]就是从[5,3]中遍历,并非从[2,5,3]中遍历。

class Solution {
    List<List<Integer>> res=new ArrayList<>();
    LinkedList<Integer> path=new LinkedList<>();
    public List<List<Integer>> combinationSum(int[] candidates, int target) {
        //candidates 中的 同一个 数字可以 无限制重复被选取 。如果至少一个数字的被选数量不同,则两种组合是不同的。 
        combinationSumBack(0,candidates,target,0);
        return res;
    }

    public void combinationSumBack(int sum,int[] candidates,int target,int startIndex){
        if(sum>target){
            return;
        }
        //终止条件:数字和为target
        if(sum==target){
            res.add(new ArrayList<>(path));
            return;
        }
        //回溯遍历过程
        for(int i=startIndex;i<candidates.length;i++){
            path.add(candidates[i]);
            sum+=candidates[i];
            combinationSumBack(sum,candidates,target,i);
            path.removeLast();
            sum-=candidates[i];
        }
    }
}

剪枝处理:

class Solution {
    public List<List<Integer>> combinationSum(int[] candidates, int target) {
        List<List<Integer>> res = new ArrayList<>();
        Arrays.sort(candidates); // 先进行排序
        backtracking(res, new ArrayList<>(), candidates, target, 0, 0);
        return res;
    }
    public void backtracking(List<List<Integer>> res, List<Integer> path, int[] candidates, int target, int sum, int idx) {
        // 找到了数字和为 target 的组合
        if (sum == target) {
            res.add(new ArrayList<>(path));
            return;
        }
        for (int i = idx; i < candidates.length; i++) {
            // 剪枝处理:如果 sum + candidates[i] > target 就终止遍历
            if (sum + candidates[i] > target) break;
            path.add(candidates[i]);
            backtracking(res, path, candidates, target, sum + candidates[i], i);
            path.remove(path.size() - 1); // 回溯,移除路径 path 最后一个元素
        }
    }
}

 

posted @ 2023-03-01 14:20  壹索007  阅读(8)  评论(0编辑  收藏  举报