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

[LeetCode] Combinations 回溯

时间:2015-03-22 00:28:37      阅读:130      评论:0      收藏:0      [点我收藏+]

标签:

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],
]

 

Hide Tags
 Backtracking
 

  这题是回溯题目,做好递归控制便可以了。
 
#include <iostream>
#include <vector>
using namespace std;

class Solution {
public:
    vector<vector<int> > combine(int n, int k) {
        vector<vector<int > > ret;
        if(n==0||k==0)  return ret;
        vector<int > curRet(k,0);
        helpFun(ret,curRet,1,n,0);
        return ret;
    }

    void helpFun(vector<vector<int > > & ret, vector<int > & curRet, int lft, int rgt,int k)
    {
        if(k==curRet.size()){
            ret.push_back(curRet);
            return ;
        }
        for(int i =lft;lft+curRet.size() - k -1   <=rgt;lft++){
            curRet[k] = lft;
            helpFun(ret,curRet,lft+1,rgt,k+1);
        }
    }
};

int main()
{
    Solution sol;
    vector<vector< int > > ret=sol.combine(4,2);
    for(int i=0;i<ret.size();i++){
        for(int j =0;j<ret[0].size();j++)
            cout<<ret[i][j]<<" ";
        cout<<endl;
    }
    return 0;
}

 

 

[LeetCode] Combinations 回溯

标签:

原文地址:http://www.cnblogs.com/Azhu/p/4356578.html

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