第十五周 leetcode 77. Combinations(Medium)
来源:互联网 发布:重庆外包网络推广 编辑:程序博客网 时间:2024/06/05 04:26
题目描述:
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],
]
解题思路:
深度优先搜索,k层深度,不够k层就回溯
代码:
class Solution {public: vector<vector<int> > combine(int n, int k) { vector<vector<int> > res; int a[k]; dfs(res,a,0,k,0,n); return res; } void dfs(vector<vector<int> > &res,int a[],int depth,int k,int cur,int n) { if(depth == k){ vector<int> temp; for(int i = 0; i < k; i++) temp.push_back(a[i]); res.push_back(temp); return ; } for(int i = cur;i < n;i++){ if(n - cur < k - depth) return ; //剩下的数凑不齐k个,回溯 a[depth] = i + 1; dfs(res,a,depth + 1,k,i + 1,n); } }};
代码运行结果:
阅读全文
0 0
- 第十五周 leetcode 77. Combinations(Medium)
- Leetcode 77. Combinations (Medium) (cpp)
- 77.leetcode Combinations(medium)[回溯递归]
- LeetCode #77 - Combinations - Medium
- Leetcode OJ 77 Combinations [Medium]
- 77. Combinations 难度:medium
- 77. Combinations -Medium
- LeetCode-77-Combinations(回溯法)-Medium
- 算法分析与设计丨第十五周丨LeetCode(19)——Longest Palindromic Substring(Medium)
- LeetCode 77. Combinations(组合)
- LeetCode刷题(C++)——Letter Combinations of a Phone Number(Medium)
- LeetCode-17- Letter Combinations of a Phone Number(查表/递归)-Medium
- <LeetCode><Medium>17Letter Combinations of a Phone Number
- Leetcode 17. Letter Combinations of a Phone Number (Medium) (cpp)
- (回溯法)LeetCode#77. Combinations
- LeetCode 77. Combinations
- [LeetCode]77.Combinations
- LeetCode --- 77. Combinations
- java Maven Tomcat JAVA_HOME not found in your environment. 错误
- 欢迎使用CSDN-markdown编辑器
- 微信开发(1)-获取openid和userinfo
- 记Linnux下C++转Windows各种心得
- Deep Neural Networks for Object Detection论文翻译
- 第十五周 leetcode 77. Combinations(Medium)
- 累
- sort3——第一次有模有样的写工程
- Redis 基础知识(5种数据类型基本操作)
- QBXT
- Farm Tour (最小费用最大流)
- 手游摇杆(一)最简单的四方向摇杆
- (gnome-ssh-askpass:24029): Gtk-WARNING **: cannot open display:
- 机器学习中的线性回归算法