[LintCode] 152. 组合

Given two integers n and k, return all possible combinations of k numbers out of 1 … n.

样例
Given n = 4 and k = 2, a solution is:

[
[2,4],
[3,4],
[2,3],
[1,2],
[1,3],
[1,4]
]

class Solution {
public:
     vector<vector<int>> ans;
     vector<int> vec;
     void dfs(int pos,int n,int k){
         if(vec.size()==k){
             ans.push_back(vec);
         }
         for(int i=pos;i<=n;i++){
             vec.push_back(i);
             dfs(i+1,n,k);
             vec.pop_back();
         }
     }
    vector<vector<int>> combine(int n, int k) {
        // write your code here
        if(k>n)return ans;
        dfs(1,n,k);
        return ans;
    }
};

猜你喜欢

转载自blog.csdn.net/a342500329a/article/details/80342977