##题目
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> tmp;
helper(n, k, 1, tmp, res);
return res;
}
void helper(int n, int k, int level, vector<int>& tmp, vector<vector<int>>& res) {
if (tmp.size() == k) res.push_back(tmp);
for (int i = level; i <= n; ++i) {
tmp.push_back(i);
helper(n, k, i + 1, tmp, res);
tmp.pop_back();
}
}
};

第二种是官方的解法,很巧妙,如下:

class Solution {
public:
vector<vector<int>> combine(int n, int k) {
vector<vector<int>> res;
vector<int> tmp(k, 0);
int i = 0;
while (i >= 0) {
++tmp[i];
if (tmp[i] > n) --i;
else if (i == k - 1) res.push_back(tmp);
else {
++i;
tmp[i] = tmp[i - 1];
}
}
return res;
}
};