LC 39. 组合总和

25 阅读2分钟

题干

给你一个 无重复元素 的整数数组 candidates 和一个目标整数 target ,找出 candidates 中可以使数字和为目标数 target 的 所有 **不同组合 ,并以列表形式返回。你可以按 任意顺序 返回这些组合。

candidates 中的 同一个 数字可以 无限制重复被选取 。如果至少一个数字的被选数量不同,则两种组合是不同的。 

对于给定的输入,保证和为 target 的不同组合数少于 150 个。

 

示例 1:

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

思路

主要考察点:回溯

  • 终止条件:总和=target
  • 集合元素:一定要设置startIndex

解题

class Solution {
    List<List<Integer>> ans= new ArrayList<List<Integer>>();
    public List<List<Integer>> combinationSum(int[] candidates, int target) {
        Arrays.sort(candidates);
        backtrace(candidates, target,0, new ArrayList<>(),0);
        return ans;
    }
    void backtrace(int[] candidates, int target,int sum,ArrayList<Integer> path,int startIndex){
        if(sum>target) return;
        if(sum==target){
            // 收集结果
            ans.add(new ArrayList<>(path));
            return;
        }
        for(int i=startIndex;i<candidates.length;i++){
            // 开始尝试
            path.add(candidates[i]);
            sum += candidates[i];
            backtrace(candidates,target,sum,path,i);
            // 尝试回退
            path.remove(path.size() - 1);
            sum-=candidates[i];
        }
        return;
    }
}

什么时候使用 used 数组,什么时候使用 begin 变量

  • 排列问题,讲究顺序(即 [2, 2, 3] 与 [2, 3, 2] 视为不同列表时),需要记录哪些数字已经使用过,此时用 used 数组;
  • 组合问题,不讲究顺序(即 [2, 2, 3] 与 [2, 3, 2] 视为相同列表时),需要按照某种顺序搜索,此时使用 begin 变量。

错题记录

// 这个不使用startIndex的代码,错在哪里?
class Solution {
    List<List<Integer>> ans= new ArrayList<List<Integer>>();
    public List<List<Integer>> combinationSum(int[] candidates, int target) {
        Arrays.sort(candidates);
        backtrace(candidates, target,0, new ArrayList<>());
        return ans;
    }
    void backtrace(int[] candidates, int target,int sum,ArrayList<Integer> path){
        if(sum>target) return;
        if(sum==target){
            // 收集结果
            ans.add(new ArrayList<>(path));
            return;
        }
        for(int i=0;i<candidates.length;i++){
            // 开始尝试
            path.add(candidates[i]);
            sum += candidates[i];
            backtrace(candidates,target,sum,path);
            path.remove(path.size() - 1);
            sum-=candidates[i];
        }
        return;
    }
}

输出

实际输出:
[[2,2,3],[2,3,2],[3,2,2],[7]]
答案:
[[2,2,3],[7]]