给定一个整数序列,求解一个子序列,子序列之和等于给定目标值。子序列满足以下条件:
1)子序列是有序的
2)子序列的元素个数不限,可以是给定元素的重复元素。
3)结果中的子序列是唯一的
原题描述如下:
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. (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]
此题很合适用回溯法来解决。调用间的关系可用调用树描述,第一层只有2,接下来,递归循环再次调用2,和为4,小于7,再次调用2,和为6,再次之后是8,大于7,因此这一层不再考虑,以此即可,如果存在等于7的就加入结果集中,这在下面的代码中很明显。
<span style="font-size:18px;">class Solution {
private:
void com(vector<int> &candidates,int start,int sum,int target,
vector<int> &path,vector<vector<int> > &res)
{
if(sum>target)
return ;
if(sum == target)
{
res.push_back(path);//加入到结果集中
return;
}
int len = candidates.size();
for(int i = start;i<len;i++)//从start开始要,基于上一次调用树
{
path.push_back(candidates[i]);
com(candidates,i,sum+candidates[i],target,path,res);//从i开始,因为小于i的都不再是正序。
path.pop_back();//有进就有出
}
}
public:
vector<vector<int> > combinationSum(vector<int> &candidates, int target) {
vector<vector<int> > res;
vector<int> path;
sort(candidates.begin(),candidates.end());
com(candidates,0,0,target,path,res);//参数设置要合理
return res;
}
};</span>