[leetcode]77. Combinations

[leetcode]77. Combinations


Analysis

waiting~—— [每天刷题并不难0.0]

Given two integers n and k, return all possible combinations of k numbers out of 1 … n.
在这里插入图片描述
排列和组合的问题好像一般都可以用递归来解决~

Implement

class Solution {
public:
    vector<vector<int>> combine(int n, int k) {
        vector<int> tmp;
        helper(tmp, 1, n, k);
        return res;
    }
    void helper(vector<int>& tmp, int start, int n, int k){
        if(k == 0){
            res.push_back(tmp);
            return ;
        }
        for(int i=start; i<=n; i++){
            tmp.push_back(i);
            helper(tmp, i+1, n, k-1);
            tmp.pop_back();
        }
    }
private:
    vector<vector<int>> res;
};

猜你喜欢

转载自blog.csdn.net/weixin_32135877/article/details/84774177