Combinations
2015-11-06 13:03
253 查看
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], ]
直接能想到的还是通过递归来做,递归到规定的深度就可以输出。但试运行时间好像不满足要求,代码如下:
class Solution { public: vector<vector<int>> combine(int n, int k) { vector<vector<int>> result; vector<int> path(k,0); build(0,k,n,1,path,result); return result; } void build(int dep, int k, int n, int index, vector<int>& path, vector<vector<int>> &result){ if(dep==k){ result.push_back(path); } for(int i=index;i<=n;i++){ path[dep]=i; build(dep+1,k,n,i+1,path,result); } } };
相关文章推荐
- 有关数据库SQL递归查询在不同数据库中的实现方法
- C#中的递归APS和CPS模式详解
- WinForm实现按名称递归查找控件的方法
- 使用SqlServer CTE递归查询处理树、图和层次结构
- C#中的尾递归与Continuation详解
- C#递归实现显示文件夹及所有文件并计算其大小的方法
- php递归创建目录的方法
- PHP递归创建多级目录
- Javascript递归打印Document层次关系实例分析
- oracle 使用递归的性能提示测试对比
- 使用curl递归下载软件脚本分享
- Perl脚本实现递归遍历目录下的文件
- JavaScript的递归之递归与循环示例介绍
- C# 递归查找树状目录实现方法
- 全排列算法的非递归实现与递归实现的方法(C++)
- php递归列出所有文件和目录的代码
- java递归菜单树转换成pojo对象
- 一个JavaScript递归实现反转数组字符串的实例
- Java中的递归详解(用递归实现99乘法表来讲解)
- C语言的递归思想实例分析