现在的位置: 首页 > 综合 > 正文

Combination Sum

2013年10月02日 ⁄ 综合 ⁄ 共 1150字 ⁄ 字号 评论关闭

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]
 

#include <algorithm>
class Solution {
public:
    vector<vector<int> > combinationSum(vector<int> &candidates, int target) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
    	vector<vector<int> > result;
		vector<int> tmp;
		std::sort(candidates.begin(),candidates.end());
		combinationSum(candidates,0,target,result,tmp);
		return result;
    }
	void  combinationSum(const vector<int> &candidates, int start,int target,   vector<vector<int> >& result,vector<int>& tmp) 
	{
		
		for(int i=start;i<candidates.size();i++)
		{
			
			int left=target-candidates[i];
			
			if(left<0)
				return ;		
			if(left==0)
			{
				tmp.push_back(candidates[i]);
				result.push_back(tmp);
				tmp.pop_back();
				return;
			}
			tmp.push_back(candidates[i]);
			combinationSum(candidates,i,left,result,tmp);
			tmp.pop_back();		
		}

		return	; 	
	}
};

抱歉!评论已关闭.