[Leetcode] - a combination of the sum (39)

The sum of a combination of (the first 39 questions fastening force)

Given a non-repeating array element candidates and a target number target, you can find all the candidates for the target numbers and combinations thereof.

Unlimited numbers of candidates may be selected is repeated.

Description:

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

Example 1:

Input: candidates = [2,3,6,7], target = 7,
the set is solved:
[
[7],
[2,2,3]
]

Example 2:

Input: candidates = [2,3,5], target = 8,
the set is solved:
[
[2,2,2,2],
[2,3,3],
[3,5]
]

Source: stay button (LeetCode)
link: combined sum

Ideas: A typical back

Code:

class Solution 
{
private:
    vector<vector<int>> vv;
public:
    vector<vector<int>> combinationSum(vector<int>& candidates, int target) 
    {
        vector<int> v;
        sort(candidates.begin(),candidates.end());
        
        dfs(0,candidates,v,target);
        return vv;
    }
    void dfs(int begin,vector<int> candidates,vector<int> v,int target)
    {
            if(target==0)
                vv.push_back(v);
            else
            {
                for(int j=begin;j<candidates.size();j++)
                {
                	if(candidates[j]<=target)
                	{
                    	v.push_back(candidates[j]);
                    	dfs(j,candidates,v,target-candidates[j]);
                    	v.pop_back();
                	}
               	   else
                    	break;
                }
            }   
     }
};

Here Insert Picture Description

Published 42 original articles · won praise 13 · views 1758

Guess you like

Origin blog.csdn.net/Vicky_Cr/article/details/105354861