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], ]
思路:
递归填数即可。
题解:
class Solution {
public:
int max;
int unused;
vector<vector<int>> ret;
vector<int> used;
void try_combine(int i)
{
if (unused == 0)
{
ret.push_back(used);
return;
}
if (i > max)
return;
try_combine(i + 1);
used.push_back(i);
--unused;
try_combine(i + 1);
used.pop_back();
++unused;
}
vector<vector<int> > combine(int n, int k) {
ret.clear();
used.clear();
max = n;
unused = k;
try_combine(1);
return ret;
}
};