题目:
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>> result;
vector<int> temp;
back(result,temp,n,k,0,1);
return result;
}
void back(vector<vector<int>> &result,vector<int> &temp, int n, int k, int count,int index)
{
if (count == k)
{
result.push_back(temp);
return;
}
if (index > n) return;
for (int i = index; i <= n; i++)
{
temp.push_back(i);
back(result,temp,n,k,count+1,i+1);
temp.pop_back();
}
}
};