题目

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:

  1. [
  2. [2,4],
  3. [3,4],
  4. [2,3],
  5. [1,2],
  6. [1,3],
  7. [1,4],
  8. ]

分析

数学领域的组合问题,求1~n中k个数的组合问题。

看到题目的条件反射就是暴力法依次列举解决问题,实际上这条道路应该是行不通的,即便是得到正确结果,时间复杂度也会很高。

仔细思考,这道题目可以用动态规划的思想解决:

1~n中k个数的所有组合一定是由两部分组成:

  1. 第一部分,求(1~n-1)中k-1个数的所有组合,然后每个组合中加入元素n;
  2. 第二部分,求(1~n-1)中k个数的所有组合;

上述两部分合并便可以得到1~n中k个数的所有组合。

算法设计需要注意几个问题,避免不必要的bug:

  1. 判断 n<=0 时,组合为空
  2. 判断 n<k 时(也就包括了 k<=0 的情况),组合均为空
  3. 判断 k==1 时, 1−n 每个元素为一个组合,返回 n 个组合
  4. 判断 n==k 时,此时只有一个组合,包括元素 1−n

AC代码

  1. class Solution {
  2. public:
  3. vector<vector<int>> combine(int n, int k) {
  4. if (n <= 0 || n < k)
  5. return vector<vector<int>>();
  6. //保存结果
  7. vector<vector<int>> ret;
  8. if (k == 1)
  9. {
  10. for (int i = 1; i <= n; i++)
  11. {
  12. vector<int> v(1,i);
  13. ret.push_back(v);
  14. }//for
  15. return ret;
  16. }//if
  17. if (n == k)
  18. {
  19. vector<int> v;
  20. for (int i = 1; i <= n; i++)
  21. {
  22. v.push_back(i);
  23. }//for
  24. ret.push_back(v);
  25. return ret;
  26. }//if
  27. else{
  28. //由两部分组成,第一部分为 1~n-1 中k-1个数的组合,每个组合加入元素n
  29. vector<vector<int>> tmp = combine(n - 1, k - 1);
  30. int len = tmp.size();
  31. for (int i = 0; i < len; i++)
  32. {
  33. tmp[i].push_back(n);
  34. ret.push_back(tmp[i]);
  35. }//for
  36. //第二部分,1~n-1中 k个数的组合,两部分合并得到最终结果
  37. tmp = combine(n - 1, k);
  38. len = tmp.size();
  39. for (int i = 0; i < len; i++)
  40. {
  41. ret.push_back(tmp[i]);
  42. }//for
  43. return ret;
  44. }//else
  45. }
  46. };

GitHub测试程序源码

LeetCode(77) Combinations的更多相关文章

  1. LeetCode(77):组合

    Medium! 题目描述: 给定两个整数 n 和 k,返回 1 ... n 中所有可能的 k 个数的组合. 示例: 输入: n = 4, k = 2 输出: [ [2,4], [3,4], [2,3] ...

  2. LeetCode(275)H-Index II

    题目 Follow up for H-Index: What if the citations array is sorted in ascending order? Could you optimi ...

  3. LeetCode(220) Contains Duplicate III

    题目 Given an array of integers, find out whether there are two distinct indices i and j in the array ...

  4. LeetCode(154) Find Minimum in Rotated Sorted Array II

    题目 Follow up for "Find Minimum in Rotated Sorted Array": What if duplicates are allowed? W ...

  5. LeetCode(122) Best Time to Buy and Sell Stock II

    题目 Say you have an array for which the ith element is the price of a given stock on day i. Design an ...

  6. LeetCode(116) Populating Next Right Pointers in Each Node

    题目 Given a binary tree struct TreeLinkNode { TreeLinkNode *left; TreeLinkNode *right; TreeLinkNode * ...

  7. LeetCode(113) Path Sum II

    题目 Given a binary tree and a sum, find all root-to-leaf paths where each path's sum equals the given ...

  8. LeetCode(107) Binary Tree Level Order Traversal II

    题目 Given a binary tree, return the bottom-up level order traversal of its nodes' values. (ie, from l ...

  9. LeetCode(4)Median of Two Sorted Arrays

    题目 There are two sorted arrays nums1 and nums2 of size m and n respectively. Find the median of the ...

随机推荐

  1. jQuery笔记之工具方法extend插件扩展

    jQuery工具方法 $.extend()插件扩展(工具方法) $.fn.extend()插件扩展(实例方法) 浅度克隆.深度克隆 两个方法基本是一样的,唯一不同的就是调用方式不一样 -------- ...

  2. CF662 C. Binary Table

    题目传送门:CF 题目大意: 给定一个\(n\times m\)的表格\((n\leqslant 20,m\leqslant 10^5)\) 每个表格中有\(0/1\),每次可以将一行或者一列翻转,问 ...

  3. 二分查找 BestCoder Round #42 1002 Gunner II

    题目传送门 /* 题意:查询x的id,每次前排的树倒下 使用lower_bound ()查找高度,f[i]记录第一棵高度为x树的位置,查询后+1(因为有序) */ #include <cstdi ...

  4. C3 Transitions, Transforms 以及 Animation总结

    C3 Transitions, Transforms 以及 Animation总结 前言 昨天有人咨询我面试的注意事项, 突然就意识到自己这块非常差, 竟然没有任何的印象, 准备看着大神老师的博客, ...

  5. AngularJS 表单验证手机号(非必填)

    代码: <form ng-app="myApp" ng-controller="validateCtrl" name="myForm" ...

  6. IOS 根据身份证号码获取 年龄 生日 性别

    /** 从身份证上获取年龄 18位身份证 */ -(NSString *)getIdentityCardAge:(NSString *)numberStr { NSDateFormatter *for ...

  7. 在colab上运行style-transfer

    1,  打开chrome浏览器,输入以下网址,打开风格转换主文件 https://colab.research.google.com/github/Hvass-Labs/TensorFlow-Tuto ...

  8. 诊断Java代码中常见的数据库性能热点问题应该这么做!

    “你的Java应用程序的性能是怎样诊断和优化的?不妨看看这两位西医的方子.如果你有更好疗效的药方,也欢迎在评论区告诉我们. 当我在帮助一些开发者或架构师分析及优化Java应用程序的性能时,关键往往不在 ...

  9. qt QTableView/QTableWidget样式设置

    转载请注明出处:http://www.cnblogs.com/dachen408/p/7591409.html 选中设置: QTableView::item:selected { background ...

  10. github 下载全部项目

    从github下载资料过程中,有些项目含有子模块,有时通过git clone 或者下载zip方式项目可能会缺少文件,因此需要执行 git submodule update --init --recur ...