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], ]
解析
很容易看出这是一个排列组合的题目,这样我们就容易联想到leetcode上的全排列问题。只不过,这是限定组合的数目。如果有写过全排列代码的,估计就很容易解决本题了。
思路:dfs
代码
class Solution {
public:
vector<vector<int>> combine(int n, int k) {
this->n=n;
this->k = k;
com(0,0);
return vvi;
}
private:
void com(int j,int t){//j奇数,t记录位置
if(j==k){
vvi.push_back(vi);
}
else{
for(int i=t;i<n;i++){
vi.push_back(i+1);
com(j+1,i+1);
vi.pop_back();
}
}
}
private:
vector<vector<int>> vvi;
vector<int> vi;
int n;
int k;
};
Custom Testcase
Run Code Result: ×
Your input
4 2Your answer
[[1,2],[1,3],[1,4],[2,3],[2,4],[3,4]]Expected answer
[[1,2],[1,3],[1,4],[2,3],[2,4],[3,4]]Runtime: 0 ms
本文介绍了一个经典的排列组合问题,即从1到n中选择k个数的所有可能组合,并提供了一种使用深度优先搜索(DFS)的解决方案。通过递归方式实现了这一过程,最终输出所有可能的组合。
542

被折叠的 条评论
为什么被折叠?



