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

 

class Solution {
public: 
    void dfs(int n,int cur,int k,int x,vector<int>&v,vector<vector<int>>&u){
        if(cur==k){
            u.push_back(v);
            return ;
        }
        for(int i=x+1;i<=n;i++){
            v.push_back(i);
            dfs(n,cur+1,k,i,v,u);
            v.pop_back();
        }
    }
    vector<vector<int>> combine(int n, int k) {
        vector<vector<int>> u;
        vector<int>v;
        dfs(n,0,k,0,v,u);
        return u;
    }
};

 

posted on 2016-04-05 18:21  Beserious  阅读(138)  评论(0编辑  收藏  举报