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],
]
For example,
If n = 4 and k = 2, a solution is:
[
[2,4],
[3,4],
[2,3],
[1,2],
[1,3],
[1,4],
]
Hide Tags Backtracking
class Solution {
public:
//如何能更好的写出递归呢,就是先画出递归图,再根据递归图写递归函数,可能会简单一点
void findKSets(vector<vector<int>> &res,vector<int> &path,int index,int k,int n)
{
if (path.size() == k)
{
res.push_back(path);
return;
}
for (int i = index ; i <= n; ++i)
{
path.push_back(i);
findKSets(res,path,i+1,k,n);
path.pop_back();
}
}
vector<vector<int>> combine(int n, int k) {
vector<vector<int>> res;
vector<int> path;
if (k > n) return res;
if (k == n)
{
for (int i = 1; i <= n; ++i)
path.push_back(i);
res.push_back(path);
return res;
}
findKSets(res, path, 1,k,n);
return res;
}
};