39. Combination Sum(Leetcode每日一题-2020.09.09)

Problem

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.

Constraints:

  • 1 <= candidates.length <= 30
  • 1 <= candidates[i] <= 200
  • Each element of candidate is unique.
  • 1 <= target <= 500

Solution

39. Combination Sum(Leetcode每日一题-2020.09.09)_第1张图片

class Solution {
     
public:
    vector<vector<int>> ret;
    vector<int> cand;
    vector<vector<int>> combinationSum(vector<int>& candidates, int target) {
     
        cand = candidates;
        vector<int> comb;
        dfs(0,comb,target);

        return ret;

    }

    void dfs(int start,vector<int> &comb,int target)
    {
     
        if(target < 0)
            return;
        if(target == 0)
        {
     
            ret.push_back(comb);
            return;
        }

        for(int i = start;i<cand.size();++i)
        {
     
            comb.push_back(cand[i]);
            dfs(i,comb,target - cand[i]);
            comb.pop_back();
        }



    }
};

你可能感兴趣的:(leetcode回溯)