[LeetCode] Combinations (bfs bad、dfs 递归 accept)

时间:2023-03-09 00:15:21
[LeetCode] Combinations (bfs bad、dfs 递归 accept)

Given two integers n and k, return all possible combinations of k numbers out of 1 ... n.

For example, If n = 4 and k = 2, a solution is:

[
[2,4],
[3,4],
[2,3],
[1,2],
[1,3],
[1,4],
]

方法1:把用queue实现bfs,改为用vector自己实现bfs,没有用额外的内存来存储中间值,但是时间上会Time Limited Exceeded!比如n=13,k=13
class Solution {
public:
vector<vector<int> > combine(int n, int k) {
vector<vector<int> > res;
if(n< || k<)
return res; vector<int> v,v0;
for(int i=;i<=n;i++){
v.push_back(i);
res.push_back(v);
v.clear();
}//end for while(!res.empty()){
v = res[];
res.erase(res.begin());
if(v.size() == k){
res.push_back(v);
break;
}else{
v0 = v;
for(int i=;i<=n;i++){
if(find(v.begin(),v.end(),i)==v.end()){
v.push_back(i);
sort(v.begin(),v.end());
if(find(res.begin(),res.end(),v)==res.end())
res.push_back(v);
v = v0;
}
}//end for
} }//end while
return res;
}//end func
};

方法2:用递归(dfs),ACCEPT!

class Solution {
public:
vector<vector<int> > combine(int n, int k) {
vector<vector<int> > result;
vector<int> v;
combination(n,k,,result,v);
return result;
}//end func
private:
void combination(int n,int k,int start,vector<vector<int> > &result,vector<int> l){
if( k == ){
result.push_back(l);
return;
} for(int i =start;i<=n;++i){
vector<int> a = l;
a.push_back(i);
combination(n,k-,i+,result,a);
}
}//end func
};