题目:
给定两个整数 n 和 k,返回范围 [1, n] 中所有可能的 k 个数的组合。
你可以按 任何顺序 返回答案。
示例 1:
输入:n = 4, k = 2
输出:
[
[2,4],
[3,4],
[2,3],
[1,2],
[1,3],
[1,4],
]
示例 2:
输入:n = 1, k = 1
输出:[[1]]
提示:
1 <= n <= 20
1 <= k <= n
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/combinations
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
回溯算法:
此题要求我们找到所有的可能的组合,我们可以用递归和回溯来解决这个问题。首先用一个暂时的容器temp来储存结果,然后从1-n开始把数值放入这个容器中直到这个容器有k个元素,这时我们找到了一个符合要求的结果,放入储存结果的集当中。如果此时的数值大于n,意味着已经超出了范围,直接返回。如果以上条件都没有,那么意味着当前的值cur符合条件,将其加入temp,随后递归下一个数值。我们需要遍历每一个可能的值,所以这里我们需要将刚放进去的cur的值移除,再递归下一个数值,这样1-n的值都会被遍历到。最后结果集会储存所有可能的符合要求的解。
代码:
class Solution {
public:
vector<vector<int>> combine(int n, int k) {
vector<int> temp;
vector<vector<int>> res;
helper(res,temp,1,n,k);
return res;
}
void helper(vector<vector<int>>& res, vector<int>& temp, int cur, int n, int total)
{
if (temp.size() == total)
{
res.push_back(temp);
return;
}
if (cur > n)
{
return;
}
// add the new cur value
temp.push_back(cur);
helper(res, temp, cur+1, n,total);
// remove the new value for next possible value
temp.pop_back();
helper(res, temp, cur+1, n,total);
}
};
这个方法其实也可以理解成dfs
参考:
https://leetcode-cn.com/problems/combinations/https://leetcode-cn.com/problems/combinations/solution/zu-he-by-leetcode-solution/