[leetcode]39. Combination Sum

链接:https://leetcode.com/problems/combination-sum/description/

Given a set of candidate numbers (candidates(without duplicates) and a target number (target), find all unique combinations in candidates where the candidate numbers sums to target.

The same repeated number may be chosen from candidates unlimited number of times.

Note:

  • All numbers (including target) will be positive integers.
  • The solution set must not contain duplicate combinations.

Example 1:

Input: candidates = [2,3,6,7], target = 7,
A solution set is:
[
  [7],
  [2,2,3]
]

Example 2:

Input: candidates = [2,3,5], target = 8,
A solution set is:
[
  [2,2,2,2],
  [2,3,3],
  [3,5]
]
class Solution {
public:
    vector<vector<int>> combinationSum(vector<int>& candidates, int target) {
        vector<vector<int>> res;
        vector<int> tmp;
        sort(candidates.begin(),candidates.end());
        dfs(res,candidates,tmp,target,0);
        return res;
    }
    
    void dfs(vector<vector<int>>& res,vector<int>& candidates,vector<int> tmp,int target,int sum)
    {
        if(sum==target)
        {  
            vector<int> tmp1=tmp;
            sort(tmp1.begin(),tmp1.end());
            if (find(res.begin(),res.end(),tmp1)==res.end())
            {
                res.push_back(tmp);
            }
            return;
        }
        if(sum>target)
        {
            return;
        }
        for(int i=0;i<candidates.size();i++)
        {
            tmp.push_back(candidates[i]);
            dfs(res,candidates,tmp,target,sum+candidates[i]);
            tmp.pop_back();
        }
    }
};

猜你喜欢

转载自blog.csdn.net/xiaocong1990/article/details/82431371