当前位置:   article > 正文

LeetCode39:组合总和

LeetCode39:组合总和

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

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

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

在这里插入图片描述
代码

class Solution {
public:
    int sum = 0;
    vector<vector<int>>  res;
    vector<int> path;
    
    void backTracking(vector<int>& candidates,int target,int startIndex) {
        
        if (sum > target)
            return;

        if (sum == target) {
            res.push_back(path);
            return;
        }

        for (int i = startIndex; i < candidates.size(); i++) {
            sum += candidates[i];
            path.push_back(candidates[i]);
            backTracking(candidates, target,i);
            sum -= candidates[i];
            path.pop_back();
            
        }
    }
    
    vector<vector<int>> combinationSum(vector<int>& candidates, int target) {
        if (candidates.size() == 0) return res;
        
        backTracking(candidates, target,0);
        return res;
    }
    
};
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34

剪枝
上个代码对于sum已经大于target的情况,其实是依然进入了下一层递归,
只是下一层递归结束判断的时候,会判断sum > target的话就返回。

对总集合排序之后,如果下一层的sum(就是本层的 sum + candidates[i])已经大于target,就可以结束本轮for循环的遍历。

class Solution {
public:
    int sum = 0;
    vector<vector<int>>  res;
    vector<int> path;

    void backTracking(vector<int>& candidates, int target, int startIndex) {

        if (sum > target)
            return;

        if (sum == target) {
            res.push_back(path);
            return;
        }

        for (int i = startIndex; i < candidates.size() && sum+candidates[i]<=target; i++) {
            sum += candidates[i];
            path.push_back(candidates[i]);
            backTracking(candidates, target, i);
            sum -= candidates[i];
            path.pop_back();

        }
    }

    vector<vector<int>> combinationSum(vector<int>& candidates, int target) {
        if (candidates.size() == 0) return res;
        sort(candidates.begin(), candidates.end());
        backTracking(candidates, target, 0);
        return res;
    }
};
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/笔触狂放9/article/detail/472826
推荐阅读
相关标签
  

闽ICP备14008679号