Leetcode 77. Combinations
来源:互联网 发布:一建试题软件 编辑:程序博客网 时间:2024/05/18 09:05
Leetcode 77. Combinations
source url
题目描述
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],]
输入:最大数字n,组合所需元素数k
输出:k个元素的排列组合
思路
利用DFS,并保存DFS的路径,在递归层满足k时,结束;否则,继续以n个节点的方式展开。由于此处是排列组合,并且不可重复,故此处根据递增的方式展开,同时进行剪支。算法复杂度
代码
class Solution {public: vector<vector<int>> ret; int dim; void backtrack(vector<int> b, int now, int n, int t){ //meet the require dimension if(dim==t){ //insert current b.push_back(now); ret.push_back(b);//insert trace }else{ b.push_back(now); //next dimension should larger than this for(int i = now+1;i<=n;i++){ backtrack(b,i,n,t+1); } } } vector<vector<int>> combine(int n, int k) { vector<int> b; dim = k; for(int i=1;i<=n;i++){ backtrack(b,i,n,1); } return ret; }};
阅读全文
0 0
- LeetCode 77. Combinations
- [LeetCode]77.Combinations
- LeetCode --- 77. Combinations
- [Leetcode] 77. Combinations
- [leetcode] 77.Combinations
- leetCode 77.Combinations (组合)
- [leetcode] 77. Combinations
- 77. Combinations LeetCode
- <LeetCode OJ> 77. Combinations
- [LeetCode]77. Combinations
- leetcode 77. Combinations
- LeetCode *** 77. Combinations
- leetcode 77. Combinations
- LeetCode 77. Combinations
- LeetCode-77.Combinations
- LeetCode 77.Combinations
- [LeetCode]problem 77. Combinations
- [LeetCode] 77. Combinations
- 这16道初级脚本算法题,你敢说全都会吗?
- bzoj4742 [Usaco2016 Dec] -- DP
- 二叉树实验报告
- 特殊的排序
- 【Unity3D】3D模型的使用——FBX的使用与Animation设置
- Leetcode 77. Combinations
- 手把手,脚把脚地教你实现网络爬虫程序(上)
- 为人处世之道
- JS中数组的方法
- SpringMVC流程架构图
- Android实现二级联动
- 最简单最全的RabbitMQ安装教程
- eclipse使用gitHub
- 《JavaScript DOM编程艺术》第十章 用javascript实现动画效果