LeetCode | 77. Combinations
来源:互联网 发布:c语言多重循环break 编辑:程序博客网 时间:2024/06/05 03:45
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],]
Solution
递归回溯,每次对目标的第Index位进行填数,因为求的是排列组合而不是全排列,所以每次只要填比之前更大的数就好,所以用“start”来记录当前填到了哪个数字。加了一个优化来提前终止不可能的尝试(比如剩下的数字不够填满剩下的空位),69 ms AC,速度挺快,排到了前10%。
Code
class Solution {public: void dfs(int Index, int start, int n, int k, vector<int> &temp, vector<vector<int> > &res)//填temp的第Index位,候选数字从start开始 { if(Index == k+1) { res.push_back(temp); temp.pop_back(); return; } for(int i=start;i<=n;i++) { if(n-start+1 < k-Index+1)//剩下的数字不够填了 break; vector<int> tt = temp; temp.push_back(i); dfs(Index+1, i+1, n, k, temp, res); temp = tt; } } vector<vector<int>> combine(int n, int k) { vector<vector<int> > res; vector<int> temp; dfs(1, 1, n, k, temp, res); return res; }};
阅读全文
1 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
- 一般报java.lang.NullPointerException的原因有以下几种
- 利用WHID为隔离主机建立隐秘通道
- TextView 代码实现drawableRight
- apache common logging和log4j区别 2016-11-01 21:01 711人阅读 评论(0) 收藏 举报 Apache common logging是一种log的框架接口,
- 使用Maven搭建SpringMVC
- LeetCode | 77. Combinations
- java后台利用正则过滤js代码
- 将Sonarqube部署到Kubernetes
- java比较日期大小及日期与字符串的转换【SimpleDateFormat操作实例】
- Nginx静态服务器配置与homestead
- thinkphp 条件数组的写法
- Android蓝牙问题
- 结构化数据转换方式之一:box-cox转换
- Python3.6:“猜数字游戏”TypeError: '<' not supported between instances of 'str' and 'int'