77. Combinations(Leetcode每日一题-2020.09.08)

Problem

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

You may return the answer in any order.

Constraints:

  • 1 <= n <= 20
  • 1 <= k <= n

Example1

Input: n = 4, k = 2
Output:
[
[2,4],
[3,4],
[2,3],
[1,2],
[1,3],
[1,4],
]

Example2

Input: n = 1, k = 1
Output: [[1]]

Solution

77. Combinations(Leetcode每日一题-2020.09.08)_第1张图片

class Solution {
     
public:
    vector<vector<int>> ret;
    vector<int> comb;
    int _k;
    int _n;
    vector<vector<int>> combine(int n, int k) {
     
        _n = n;
        _k = k;

        dfs(1);

        return ret;

    }

    void dfs(int start)
    {
     
        if(comb.size() == _k)
        {
     
            ret.push_back(comb);
            return;
        }

        for(int i = start;i<=_n;++i)
        {
     
            comb.push_back(i);
            dfs(i+1);
            comb.pop_back();
        }

    }
};

你可能感兴趣的:(leetcode回溯)