39. Combination Sum
方法一 回溯:
思路参考
bool backtrack(vector<vector<int>> &out,vector<int> tmp,vector<int>& nums, int remain,int start){
if(remain<0)
return false;
else if(remain==0){
out.push_back(tmp);
return false;
}
else{
for(int i=start;i<nums.size();i++){
bool flag;
tmp.push_back(nums[i]);
flag=backtrack(out,tmp,nums,remain-nums[i],i);
tmp.pop_back();
if(!flag)
break;
}
return true;
}
}
vector<vector<int>> combinationSum(vector<int>& candidates, int target) {
sort(candidates.begin(),candidates.end());
vector<vector<int>> out;
vector<int> tmp;
backtrack(out,tmp,candidates,target,0);
return out;
}
方法二 非递归
TIP:思路跟回溯法相同,但是需要注意,当结果大于等于目标值所以栈顶数字弹出时,下一个要进栈的元素是到底哪一个。因此这里使用两个栈,一个存放数字,一个存放下标,就可以实现判断。
vector<vector<int> > combinationSum(vector<int> &candidates, int target)
{
sort(candidates.begin(), candidates.end());
vector<int> tmp;
vector<vector<int> > result;
vector<int> index;
for (int i = 0; i < candidates.size(); )
{
if(target <= candidates[i])
{
//找到结果,保存,但是不入栈
if (target == candidates[i])
{
tmp.push_back(candidates[i]);
result.push_back(tmp);
tmp.pop_back();
}
//特殊情况-没有解或一个解
if(tmp.empty()) return result;
i = index.back()+1;
target += tmp.back();
tmp.pop_back();
index.pop_back();
while (i == candidates.size())//坑
{
//注意:都需要判断空栈的时候返回值
if(tmp.empty()) return result;
i = index.back()+1;
target += tmp.back();
tmp.pop_back();
index.pop_back();
}
}
else
{
tmp.push_back(candidates[i]);
index.push_back(i);
target -= candidates[i];
}
}
return result;
}
40. Combination Sum II
想尝试非递归方法,太多坑了,以至于代码有点乱,不过击败99%
标注在代码里了
vector<vector<int>> combinationSum2(vector<int>& candidates, int target) {
sort(candidates.begin(), candidates.end());
vector<int> tmp;
vector<vector<int> > result;
vector<int> index;
if(candidates.size()==1 && target>candidates[0]){ //输入一个数字且比目标值小时
return result;
}
for (int i = 0; i < candidates.size(); ) {
if(target <= candidates[i]) {
if (target == candidates[i]) {
tmp.push_back(candidates[i]);
result.push_back(tmp);
tmp.pop_back();
}
if(tmp.empty()) return result;
i = index.back()+1;
target += tmp.back();
tmp.pop_back();
index.pop_back();
while(i<candidates.size() && candidates[i]==candidates[i-1]) //每次某个数弹出时,如果下一个数相等,那么就不看,避免重复
//用的是while不是if,可能有很多个,坑!
++i;
while (i == candidates.size()) {//大坑
if(tmp.empty()) return result;
i = index.back()+1;
while(i<candidates.size() && candidates[i]==candidates[i-1]) //每当i向后看时都需要检测!!
++i;
target += tmp.back();
tmp.pop_back();
index.pop_back();
}
}
else {
if((i+1)!=candidates.size() || tmp.empty()){
tmp.push_back(candidates[i]);
index.push_back(i);
target -= candidates[i];
++i;
}
else{
target+=tmp.back();
i=index.back()+1;
while(i<candidates.size() && candidates[i]==candidates[i-1])
++i;
index.pop_back();
tmp.pop_back();
while (i == candidates.size()) { //让然要考虑越界的情况
if(tmp.empty()) return result;
i = index.back()+1;
while(i<candidates.size() && candidates[i]==candidates[i-1])
++i;
target += tmp.back();
tmp.pop_back();
index.pop_back();
}
}
}
}
return result;
}