LeetCode77——Combinations

不念不忘少年蓝@ 2022-08-10 09:20 255阅读 0赞

LeetCode77——Combinations

题意:

两个数字n和k,找出所有这样的组合:

1.组合中有k个数字

2.组合是递增

3.组合中的数字是{1,2,3,….n} 的子集

为了叙述方便,假设子集为D,子集的大小为k。

那就是回溯了,对D中所有的数字进行k阶全排列,但这个全排列要排除非增序的组合。

代码:

  1. class Solution {
  2. private:
  3. void help(int i,int n, int k,vector<int>temp,vector<vector<int>>&result)
  4. {
  5. if (temp.size() == k)//k个数
  6. {
  7. result.push_back(temp);
  8. return;
  9. }
  10. if (temp.size() > 1 && temp.back() < *(temp.end()-2))//递增
  11. return;
  12. for (int index = i+1; index < n+1; index++)//i
  13. {
  14. temp.push_back(index);
  15. help(index , n, k, temp, result);//递归
  16. temp.pop_back();//一次完成要弹出
  17. }
  18. }
  19. public:
  20. vector<vector<int>> combine(int n, int k) {
  21. vector<int> temp;
  22. vector<vector<int>>result;
  23. help(0, n, k, temp, result);
  24. return result;
  25. }
  26. };

发表评论

表情:
评论列表 (有 0 条评论,255人围观)

还没有评论,来说两句吧...

相关阅读