LeetCode | 0077. Combinations组合【Python】
LeetCode 0077. Combinations组合【Medium】【Python】【回溯】
Problem
LeetCode
Given two integers n and k, return all possible combinations of k numbers out of 1 … n.
Example:
Input: n = 4, k = 2
Output:
[[2,4],[3,4],[2,3],[1,2],[1,3],[1,4],
]
问题
力扣
给定两个整数 n 和 k,返回 1
if name == "__main… n 中所有可能的 k 个数的组合。
示例:
输入: n = 4, k = 2
输出:
[[2,4],[3,4],[2,3],[1,2],[1,3],[1,4],
]
思路
回溯
回溯三步骤
1.有效结果:path 长度等于 k。
2.回溯范围及答案更新。
3.剪枝条件:经过分析,可以发现 i 应该 <= n - (k - len(path)) + 1。
详细分析可以参考 liweiwei1419 的题解(在最后)。
Python3代码
class Solution:def combine(self, n: int, k: int) -> List[List[int]]:# special judgmentif n <= 0 or k <= 0 or k > n:return []res = []self.dfs(1, k, n, [], res)return resdef dfs(self, start, k, n, path, res):# 1.valid resultif len(path) == k:res.append(path[:])return# 3.pruningfor i in range(start, n - (k - len(path)) + 2):# 2.backtrack and updatepath.append(i)self.dfs(i + 1, k, n, path, res)path.pop()
代码地址
GitHub链接
参考
liweiwei1419 题解
LeetCode | 0077. Combinations组合【Python】相关推荐
- Leetcode 77. Combinations 组合
Leetcode 77. Combinations 组合 标签 : Leetcode 题目地址: https://leetcode-cn.com/problems/combinations/ 题目描述 ...
- 【LeetCode】#39组合总和(Combination Sum)
[LeetCode]#39组合总和(Combination Sum) 加粗样式 给定一个无重复元素的数组 candidates 和一个目标数 target ,找出 candidates 中所有可以使数 ...
- LeetCode 其他部分 简单 Python实现
#LeetCode 其他部分 简单 Python实现 ''' 位1的个数 编写一个函数,输入是一个无符号整数,返回其二进制表达式中数字位数为 '1' 的个数(也被称为汉明重量).示例 : 输入: 11 ...
- 【DFS】LeetCode 77. Combinations
LeetCode 77. Combinations Solution1:我的答案 DFS,时间复杂度O(n!)O(n!)O(n!),空间复杂度O(n)O(n)O(n) class Solution { ...
- LeetCode Combinations (组合)
问题:给出n,k,要求输出从1到n选取k个数的所有组合 思路:使用dfs,第一层是从1到n中选取一个数,第二层是从基于上一层选取的数+1到n中选取一个数,依次类推. 具体代码参考: https://g ...
- LeetCode 77. 组合 | Python
77. 组合 题目来源:力扣(LeetCode)https://leetcode-cn.com/problems/combinations 题目 给定两个整数 n 和 k,返回 1 - n 中所有可能 ...
- LeetCode Letter Combinations of a Phone Number 电话号码组合
题意:给一个电话号码,要求返回所有在手机上按键的组合,组合必须由键盘上号码的下方的字母组成. 思路:尼玛,一直RE,题意都不说0和1怎么办.DP解决. 1 class Solution { 2 pub ...
- [leetcode] 77. Combinations @ python
原题 Given two integers n and k, return all possible combinations of k numbers out of 1 - n. Example: ...
- LeetCode刷题之python解法(持续更新)
1. Two Sum 4行 class Solution:def twoSum(self, nums: List[int], target: int) -> List[int]:d = {}fo ...
最新文章
- case when条件表达式
- swagger2注解说明文档
- 判断使用设备是PC还是phone
- 【Step by Step】编写代码验证一个ASP.NET应用程序和页面的生命周期
- GitHub上的私有仓库转换为共有仓库以及共有仓库转换为私有仓库
- 利用mfc项目opengl旋转正方形_C++学习之路:适合C++新手的练手项目,高薪之路必备项目...
- Ubuntu18.04中安装virtualenv和virtualenvwrapper
- 地址后面的sessionid怎么消除_富贵包的消除和改善头前倾,通过运动和减肥可以吗?...
- 统计报表币种金额_海关总署就全面发布以人民币计价统计数据答问
- Matlab中的plotyy用法总结
- maven-assembly-plugin
- 作为泛娱乐圈专属域名,.fans岂能错过这匹年末综艺“黑马”?
- 个人学习(解决)练习ssm框架遇到的问题No qualifying bean of type ‘service.BookTypeService‘ available:
- 杰理AC692X学习-BLE与APP端发送与接收
- JAVA的向上转型与向下转型(二)
- 【屌丝之作】3D遥控坦克大战
- python实现图片拼接(项目界面展示图合并)
- 笙默考试管理系统——管理员桌面、桌面方法
- word 分章节,如何下一章页眉单独改动,不影响上一章
- 风的UV分量转成风向风速(C#)