[LeetCode] Combinations

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],
]

 给定n和k,从1~n中选择k个数作为组合数,并输出。

这是一个回溯问题,重点在于构造回溯辅助函数。
对于n=4,k=2,在1、2、3、4中选择2个数字,
举个例子,选定第一个数1,这时k=1,只需要再选择一个数即可。将选择后的组合放入数组。
当k=0时表面以及选择完毕,当k<0表示返回该数组。引入一个idx变量来避免重复选择。

class Solution {
public:
    vector<vector<int>> combine(int n, int k) {
        vector<vector<int>> res;
        vector<int> tmp;
        int idx = 1;
        helper(n, k, idx, tmp, res);
        return res;
    }
    
    void helper(int n, int k, int idx, vector<int>& tmp, vector<vector<int>>& res) {
        if (k < 0) {
            return;
        }
        else if (k == 0) {
            res.push_back(tmp);
        }
        else {
            for (int i = idx; i <= n; i++) {
                tmp.push_back(i);
                helper(n, k - 1, i + 1, tmp, res);
                tmp.pop_back();
            }
        }
    }
};
// 82 ms
原文地址:https://www.cnblogs.com/immjc/p/8353348.html