码迷,mamicode.com
首页 > 其他好文 > 详细

[LeetCode] Combinations (bfs)

时间:2014-08-14 20:26:49      阅读:202      评论:0      收藏:0      [点我收藏+]

标签:style   blog   color   os   io   for   ar   div   

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),布布扣,bubuko.com

[LeetCode] Combinations (bfs)

标签:style   blog   color   os   io   for   ar   div   

原文地址:http://www.cnblogs.com/Xylophone/p/3913161.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!