描述
Given two integers n and k, return all possible combinations of k numbers out of 1 ... n.
You don't need to care the order of combinations, but you should make sure the numbers in a combination are sorted.
您在真实的面试中是否遇到过这个题?
是
样例
Given n = 4
and k = 2
, a solution is:
[
[2,4],
[3,4],
[2,3],
[1,2],
[1,3],
[1,4]
]
分析:
这道题让求1到n共n个数字里k个数的组合数的所有情况,还是要用深度优先搜索DFS来解,根据以往的经验,像这种要求出所有结果的集合,一般都是用DFS调用递归来解。那么我们建立一个保存最终结果的大集合res,还要定义一个保存每一个组合的小集合out,每次放一个数到out里,如果out里数个数到了k个,则把out保存到最终结果中,否则在下一层中继续调用递归。网友u010500263的博客里有一张图很好的说明了递归调用的顺序
代码:
class Solution {
public:
/**
* @param n: Given the range of numbers
* @param k: Given the numbers of combinations
* @return: All the combinations of k numbers out of 1..n
*/
vector<vector<int>> combine(int n, int k) {
// write your code here
vector<vector<int> >result;
vector<int>temp;
helper(n,k,1,result,temp);
return result;
}
void helper(int n,int k,int level,vector<vector<int> >&result,vector<int>&temp)
{
if(temp.size()==k) result.push_back(temp);
else
for(int i=level;i<=n;i++)
{
temp.push_back(i);
helper(n,k,i+1,result,temp);
temp.pop_back();
}
}
};
递归过程: