算法思路汇总:39.组合总和

140 阅读2分钟

39.组合总和

「这是我参与2022首次更文挑战的第20天,活动详情查看:2022首次更文挑战」。

难度:mid 来源:力扣(LeetCode)

题目:

给你一个 无重复元素 的整数数组 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 。仅有这两种组合。

示例 2:

输入: candidates = [2,3,5], target = 8 输出: [[2,2,2,2],[2,3,3],[3,5]]

示例 3:

输入: candidates = [2], target = 1 输出: []

提示:

  1. 1 <= candidates.length <= 30
  2. 1 <= candidates[i] <= 200
  3. candidate 中的每个元素都 互不相同
  4. 1 <= target <= 500

思路:

查看题目可知,还是求组合问题,那么首先创建两个集合,一个 res ,一个path集合。

List<List<Integer>> res = new ArrayList<>();
LinkedList<Integer> path = new LinkedList<>();

确定好保存的方式,然后考虑以下问题:

  1. 递归的结束条件
  2. 传递的参数问题
  3. 单层递归逻辑

为什么需要采用递归的形式,如果采用for循环,那么需要嵌套好多层,容易爆掉,并且嵌套次数还不好控制。

明确结束条件,题目中给出target,我们只需要每次target-candidates[i]==0;那么就满足条件,进行保存path;如果target < 0,则直接结束本次递归即可;

if(target < 0) return;
if(target == 0){
    res.add(new ArrayList<>(path));
    return;
}

怎么来判断传递的参数呢,在单次递归过程中需要用到的参数,那么我们就需要传递过来,

怎么写递归过程,需要明确一个点:

  1. 递归的宽度

在此题目中递归的宽度就是数组的长度,所以我们需要传递一个candidates.length;

我们如何控制下一次的元素满足要求;

以[2,3,6,7]为例

即:如果本次使用的元素为2下标为0,那么下一次需要使用的元素为【2,3,6,7】对应下标【0,1,2,3】;

由于题目要求中说同一个 数字可以 无限制重复被选取,所以使用的元素2还可以在下次递归中使用。但是不能使用该数字的前面的元素。

由此我们需要一个index来控制下次需要遍历的起始地址,具体代码如下所示:

for(int i = index; i < len; i++){
    path.add(candidates[i]);
    combina(candidates,len,target-candidates[i],i);
    path.removeLast();
}

完整代码:

class Solution {
    List<List<Integer>> res = new ArrayList<>();
    LinkedList<Integer> path = new LinkedList<>();
    public List<List<Integer>> combinationSum(int[] candidates, int target) {
        int len  = candidates.length;
        combina(candidates,len,target,0);
        return res;
    }
    void combina(int[] candidates,int len,int target,int index){
        if(target < 0) return;
        if(target == 0){
            res.add(new ArrayList<>(path));
            return;
        }
        for(int i = index; i < len; i++){
            path.add(candidates[i]);
            combina(candidates,len,target-candidates[i],i);
            path.removeLast();
        }
    }
}