[LeetCode] 77. Combinations

来源:互联网 发布:流体力学软件fluent 编辑:程序博客网 时间:2024/06/06 01:18

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:    vector<vector<int>> combine(int n, int k) {        vector<vector<int>> res;        vector<int> comb;        combine(res, comb, 1, n, k);        return res;    }private:    void combine(vector<vector<int>>& res, vector<int>& comb, int base, int n, int k) {        if (k == 0) {            res.push_back(comb);            return;        }        for (int num = base; n + 1 - num >= k; num++) {            comb.push_back(num);            combine(res, comb, num + 1, n, k - 1);            comb.pop_back();        }    }};

这里写图片描述这里写图片描述