[LeetCode] Combinations 回溯

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)