• 39. 组合总和


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

    candidates 中的数字可以无限制重复被选取。

    说明:

    所有数字(包括 target)都是正整数。
    解集不能包含重复的组合。 
    示例 1:

    输入:candidates = [2,3,6,7], target = 7,
    所求解集为:
    [
    [7],
    [2,2,3]
    ]
    示例 2:

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

    来源:力扣(LeetCode)
    链接:https://leetcode-cn.com/problems/combination-sum
    著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

    class Solution {
    public:
        void dfs(vector<int>& candidates,int target,vector<int>& cur,vector<vector<int>>& res)
        {
            if(target<0)return;
            if(target==0)
            {
                res.push_back(cur);
                return;
            }
            for(int i=0;i<candidates.size()&&candidates[i]<=target;i++)
            {
                //如果当前选中的比上一个选中的要小 则剪枝
                if(cur.size()&&candidates[i]<cur.back())continue;
                cur.push_back(candidates[i]);
                dfs(candidates,target-candidates[i],cur,res);
                cur.pop_back();
            }
        }
        vector<vector<int>> combinationSum(vector<int>& candidates, int target) {
            sort(candidates.begin(),candidates.end());
            vector<vector<int>> res;
            vector<int> cur;
            dfs(candidates,target,cur,res);
            return res;
        }
    };
  • 相关阅读:
    Cheatsheet: 2010 05.25 ~ 05.31
    Cheatsheet: 2010 07.01 ~ 07.08
    Cheatsheet: 2010 07.22 ~ 07.31
    Cheatsheet: 2010 06.01 ~ 06.07
    Cheatsheet: 2010 05.11 ~ 05.17
    Cheatsheet: 2010 06.08 ~ 06.15
    Cheatsheet: 2010 06.16 ~ 06.22
    Cheatsheet: 2010 06.23 ~ 06.30
    2020.7.20第十五天
    2020.7.19第十四天
  • 原文地址:https://www.cnblogs.com/lancelee98/p/13347217.html
Copyright © 2020-2023  润新知