题目:
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]
思路:
还是回溯的思想。
用一个指针index从第一个元素开始,遍历到最后一个。当遍历到某一个元素时,我们从这个元素开始向前回溯。
为了后面出现重复,先把该元素存入temp字符串,然后target=target-candidates[index]。
下一步,back(candidates,target-candidates[index],index,temp,result);
temp.pop_back();一定要删除上一个元素,才能回溯到前一种情况
下一步,back(candidates,target,index-1,temp,result);即从前一个元素开始往前回溯。
如果最后的元素与target相等,则将temp存入result。
可惜这样有个缺陷,就是存入的不是按递增的顺序,而是递减的顺序,这样还需将每个字符串反序。
后面我再想想有没有更好的解法。
class Solution
{
public:
vector<vector<int>> combinationSum(vector<int>&candidates,int target)
{
vector<vector<int>> result;
vector<int> temp;
int size=candidates.size();
if(size==0) return result;
sort(candidates.begin(),candidates.end());
for(int i=0;i<size;i++)
{
if(candidates[i]==target)
{
temp.push_back(candidates[i]);
result.push_back(temp);
temp.pop_back();
}
temp.push_back(candidates[i]);//先必须至少包含一个,防止重复
back(candidates,target-candidates[i],i,temp,result);
temp.pop_back();
}
for(int i=0;i<result.size();i++)
converse(result[i]);
return result;
}
void back(vector<int>&candidates,int target,int index,vector<int>&temp,vector<vector<int>>&result)
{
if(index<0) return;
if(target<0) return;
if(candidates[index]==target)
{
temp.push_back(candidates[index]);
result.push_back(temp);
temp.pop_back(); //回溯
back(candidates,target,index-1,temp,result);
return;
}
temp.push_back(candidates[index]);
back(candidates,target-candidates[index],index,temp,result);
temp.pop_back(); //回溯
back(candidates,target,index-1,temp,result);
return;
}
void converse(vector<int>& temp)
{
int size=temp.size();
if(size<2) return;
int i=0,j=size-1;
while(i<j)
{
int a=temp[i];
temp[i]=temp[j];
temp[j]=a;
i++;j--;
}
}
};