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<1 || k<1) return res; vector<int> v,v0; for(int i=1;i<=n;i++){ v.push_back(i); res.push_back(v); v.clear(); }//end for while(!res.empty()){ v = res[0]; res.erase(res.begin()); if(v.size() == k){ res.push_back(v); break; }else{ v0 = v; for(int i=1;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,1,result,v); return result; }//end func private: void combination(int n,int k,int start,vector<vector<int> > &result,vector<int> l){ if( k == 0 ){ result.push_back(l); return; } for(int i =start;i<=n;++i){ vector<int> a = l; a.push_back(i); combination(n,k-1,i+1,result,a); } }//end func };