问题描述:
Given two integers n and k, return all possible combinations of k numbers out of 1 ... n.
示例:
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> com;
int start = 1;
bs(res, n, k, com, start);
return res;
}
void bs(vector<vector<int>>& res, int n, int k, vector<int>& com, int start)
{
if (k == 0)
{
res.push_back(com);
return;
}
for (int i = start; i <= n; i++)
{
com.push_back(i);
bs(res, n, k - 1, com, i + 1);
com.pop_back();
}
}
};