Combination Sum

难度:2

- -本来想用背包做,发现用来做这题好麻烦,最后还是DFS裸搜了

个人总结:1Y达成

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

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

Note:

  • All numbers (including target) will be positive integers.
  • Elements in a combination (a1a2, … , ak) must be in non-descending order. (ie, a1 ≤ a2 ≤ … ≤ ak).
  • The solution set must not contain duplicate combinations.

For example, given candidate set 2,3,6,7 and target 7
A solution set is: 
[7] 
[2, 2, 3] 

class Solution 
{
public:
	vector<vector<int> >ans;
	vector<int>tmp;
	void dfs(int left, int cur_index,vector<int> &candidates)
	{
		if(left == 0)	{ans.push_back(tmp);return;}
		for(int i=cur_index;i<candidates.size();i++)
		{
			if(left-candidates[i] >= 0)
			{
				tmp.push_back(candidates[i]);
				dfs(left-candidates[i],i,candidates);
				tmp.pop_back();
			}
		}
	}
    vector<vector<int> > combinationSum(vector<int> &candidates, int target) 
	{
		sort(candidates.begin(),candidates.end());
		candidates.erase(unique(candidates.begin(),candidates.end()),candidates.end());
		ans.clear();
		tmp.clear();
		dfs(target,0,candidates);
		return ans;
    }
};


你可能感兴趣的:(Combination Sum)