一. 题目描述
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 (a1; a2; … ; ak) must be in non-descending order. (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]
二. 题目分析
题目大意是:有一个正整数集合C,和一个正整数目标T。现从C中选出一些数,使其累加和恰好等于T(C中的每个数都可以取若干次),求所有不同的取数方案。一道典型的DFS题。
三. 示例代码
// 来源:http://blog.csdn.net/doc_sgl/article/details/12283675
#include <vector>
#include <algorithm>
#include <iostream>
using namespace std;
class Solution
{
private:
void comb(vector<int> candidates, int index, int sum, int target, vector<vector<int>> &res, vector<int> &path)
{
if(sum>target)return;
if(sum==target){res.push_back(path);return;}
for(int i= index; i<candidates.size();i++)
{
path.push_back(candidates[i]);
comb(candidates,i,sum+candidates[i],target,res,path);
path.pop_back();
}
}
public:
vector<vector<int> > combinationSum(vector<int> &candidates, int target) {
// Note: The Solution object is instantiated only once.
sort(candidates.begin(),candidates.end());
vector<vector<int>> res;
vector<int> path;
comb(candidates,0,0,target,res,path);
return res;
}
};
四. 小结
最近比较忙碌,只能先借鉴别人的代码进行学习,后续要深入研究。
原文:http://blog.csdn.net/liyuefeilong/article/details/50044961