[Leetcode] combinations 组合

时间:2023-03-09 09:14:18
[Leetcode] 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],
]

题意:给定1...n个数,求出每k个数的组合情况。

思路:使用DFS。定义中间数组变量,每当其大小为k时,将其存入结果res;若不等于则继续调用。需要注意的是,组合是不讲究顺序的,所以下层的递归不用从头开始,只需从当前的下一个数字开始就行,另外,对第一层的选取,使用迭代,这样就可以考虑到所有情况,后面的从下层开始,用递归就好。这里有详细的解释。代码如下:

 class Solution {
public:
vector<vector<int> > combine(int n, int k)
{
vector<vector<int>> res;
vector<int> midRes;
combineDFS(n,k,,midRes,res);
return res;
} void combineDFS(int n,int k,int beg,vector<int> &midRes,vector<vector<int>> &res)
{
if(midRes.size()==k)
{
res.push_back(midRes);
}
else
{
for(int i=beg;i<=n;++i)
{
midRes.push_back(i);
combineDFS(n,k,i+,midRes,res);
midRes.pop_back();
}
}
}
};

注:排列和组合的区别在于和顺序有关,如:[1,2]、[2,1]是两种不同的排列,却是相同的组合。