# leetcode 39 dfs leetcode 40 dfs

leetcode 39

class Solution {
vector<vector<int>>ret;
vector<int>temp;
vector<int> srt;
public:
vector<vector<int>> combinationSum(vector<int>& candidates, int target) {
srt=candidates;
sort(srt.begin(),srt.end());
dfs(target,0); //从下标0开始，杜绝0 1 ,1 0下这样的重复
return ret;
}
void dfs(int target,int index){
if(target==0)
{
ret.push_back(temp);
return;
}
for(int i=index;i<srt.size()&&(target-srt[i]>=0);i++)
{
temp.push_back(srt[i]);
dfs(target-srt[i],i);
temp.pop_back();
}
return;
}

};

leetcode 40

class Solution {
vector<vector<int>>ret;
vector<int>temp;
vector<int> srt;
public:
vector<vector<int>> combinationSum2(vector<int>& candidates, int target) {
srt=candidates;
sort(srt.begin(),srt.end());
dfs(target,0); //从下标0开始，杜绝0 1 ,1 0下这样的重复
return ret;
}
void dfs(int target,int index){
if(target==0)
{
//vector<vector<int>> :: itrator it;
if(find(ret.begin(),ret.end(),temp)==ret.end())
ret.push_back(temp);
return;
}
for(int i=index;i<srt.size()&&(target-srt[i]>=0);i++)
{
temp.push_back(srt[i]);
dfs(target-srt[i],i+1);
temp.pop_back();
}
return;
}
};

class Solution {
vector<vector<int>>ret;
vector<int>temp;
int tp;
vector<int> srt;
int tar;
public:
vector<vector<int>> combinationSum2(vector<int>& candidates, int target) {
srt=candidates;
sort(srt.begin(),srt.end());
tar=target;
dfs(target,0); //从下标0开始，杜绝0 1 ,1 0下这样的重复
return ret;
}
void dfs(int target,int index){
if(target==0)
{
//vector<vector<int>> :: itrator it;
//if(find(ret.begin(),ret.end(),temp)==ret.end())
ret.push_back(temp);
return;
}
for(int i=index;i<srt.size()&&(target-srt[i]>=0);i++)
{
if(i>index&&srt[i]==srt[i-1])  //index表示的是当前target对应的，开始的位置,后续如果==index，对于同一个target会形成重复;若是不同target不会重复
continue;
temp.push_back(srt[i]);
dfs(target-srt[i],i+1);
temp.pop_back();
}
return;
}
};

posted @ 2019-11-19 23:59  Eriovar  阅读(...)  评论(... 编辑 收藏
Live2D
//鼠标