[LintCode] 152. 组合

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/a342500329a/article/details/80342977

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;
    }
};
阅读更多
换一批

没有更多推荐了,返回首页