Given two integers n and k, return all possible combinations of k numbers out of 1 ... n.
Example:
Input: n = 4, k = 2 Output: [ [2,4], [3,4], [2,3], [1,2], [1,3], [1,4], ]
求组合数。
思路:递归+深度优先搜索(DFS)
先在第一个位置放一个数,然后在第二个位置放剩下可能的数,依次类推。
某个位置的某个数后续情况遍历完,要弹出,放下一个数
class Solution {
public:
vector<vector<int>> combine(int n, int k) {
vector<vector<int> > res;
vector<int> out;
helper(n, k, 1, res, out);
return res;
}
void helper(int n, int k, int start, vector<vector<int> > &res, vector<int> &out) {
if (out.size() == k)
res.push_back(out);
for (int i = start; i <= n; i++) {
out.push_back(i);
helper(n, k, i + 1, res, out);
out.pop_back();//弹出 放下一个可能的数
}
}
};