Combination Sum

class Solution {
private:
	vector<int> c;
	vector<vector<int> > res;  //保存最后结果
public:
	vector<vector<int> > combinationSum(vector<int> &candidates, int target) {
		vector<int> a;
		sort(candidates.begin(), candidates.end()); //先对C中候选数升序排序,为后面的剪枝做准备
		c = candidates;
		backtrack(a, 0, target);
		//for(vector<int> &m:res)
	    //sort(m.begin(), m.end());
		//res.erase(unique(res.begin(), res.end()), res.end());
		return res;
	}
	int sum(vector<int>& a){
		int res = 0;
		for (int i = 0; i<a.size(); i++){
			res += a[i];
		}
		return res;
	};
	void backtrack(vector<int>& a, int k, int target)
	{
		if (k == c.size()) return;
		if (sum(a) == target){
			res.push_back(a);
			return;
		}
		else if (sum(a)>target)
			return;
		else {
			//k = k + 1;
			for (int i = k; i<c.size(); i++) {
				//a[k] = c[i];
				a.push_back(c[i]);
				backtrack(a, i, target);
				a.pop_back();

			}
		}
	}
};

阅读更多
文章标签: leetcode
个人分类: leetcode
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

加入CSDN,享受更精准的内容推荐,与500万程序员共同成长!
关闭
关闭