给定两个整数 n 和 k,返回 1 … n 中所有可能的 k 个数的组合。
示例:
输入: n = 4, k = 2
输出:
[
[2,4],
[3,4],
[2,3],
[1,2],
[1,3],
[1,4],
]
使用回溯的方法,如果满足条件就将其保存。否则就返回到上一步接着进行。
另外两个用回溯法的题
Leetcode 39组合总和 C++ 回溯法
LeetCode 40 组合总和 C++ 回溯法
class Solution {
public:
vector<vector<int>> combine(int n, int k) {
vector<vector<int>> res;
vector<int> temp;
fun(n,k,1,temp,res);
return res;
}
//这里函数temp可以定义为引用,也可以定义为拷贝。但是定义为引用速度快,不占内存
void fun(int n,int k,int index,vector<int> &temp,vector<vector<int>> &res)
{
if(temp.size()==k)
{
res.push_back(temp);
return;
}
while(index<=n)
{
temp.push_back(index);
fun(n,k,index+1,temp,res);
temp.pop_back();//注意
++index;
}
}
};