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], ] 方法:把用queue实现bfs,改为用vector自己实现bfs,没有用额外的内存来存储中间值:
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 };
[LeetCode] Combinations (bfs)
时间: 2024-12-17 23:34:15