[LeetCode]题解(python):077-Combinations
2015-12-30 13:15
513 查看
[b]题目来源:[/b]
https://leetcode.com/problems/combinations/
[b]题意分析:[/b]
给定一个n和k,输出1到n的所有k个数的组合。比如n = 4,k=2
[b]题目思路:[/b]
这道题目用递归的思想来做。比如我们把n当成一个数字[1,2,...,n],如果组合包括1那么[2,..,n]和k-1的所有答案添加一个1;如果组合不包括1,那么答案是[2,...,n]和k的组合。然后将两个组合结合起来就可以了。初始化,如果n == k,那么组合就是直接所有的数,如果k == 1,那么组合是每一个数。
[b]代码(Python):[/b]
View Code
转载请注明出处:http://www.cnblogs.com/chruny/p/5088520.html
https://leetcode.com/problems/combinations/
[b]题意分析:[/b]
给定一个n和k,输出1到n的所有k个数的组合。比如n = 4,k=2
[ [2,4], [3,4], [2,3], [1,2], [1,3], [1,4], ]
[b]题目思路:[/b]
这道题目用递归的思想来做。比如我们把n当成一个数字[1,2,...,n],如果组合包括1那么[2,..,n]和k-1的所有答案添加一个1;如果组合不包括1,那么答案是[2,...,n]和k的组合。然后将两个组合结合起来就可以了。初始化,如果n == k,那么组合就是直接所有的数,如果k == 1,那么组合是每一个数。
[b]代码(Python):[/b]
class Solution(object): def combine(self, n, k): """ :type n: int :type k: int :rtype: List[List[int]] """ def solve(index,n,k): ans = [] if k == n - index + 1: t = [] for i in range(k): t.append(index) index += 1 ans.append(t) return ans if k == 1: while index <= n: ans.append([index]) index += 1 return ans tmp1,tmp2 = solve(index + 1,n,k),solve(index + 1,n,k-1) for i in tmp1: ans.append(i) for i in tmp2: i = [index] + i ans.append(i) return ans return solve(1,n,k)
View Code
转载请注明出处:http://www.cnblogs.com/chruny/p/5088520.html
相关文章推荐
- Python 第二章 函数
- [LeetCode]题解(python):076-Minimum Window Substring
- caffe 如何调用python层
- Caffe学习系列(13):数据可视化环境(python接口)配置
- python AES-16位加密解密功能实现
- Python 获取Twitter用户与Friends和Followers的关系(eg, 交集,差集)
- 仿射变换(Affine transformation)与python实践
- python 字典排序
- python手记(51)
- Python 1.6 使用dict和set
- [python] 专题八.多线程编程之thread和threading
- python模拟登陆和发布信息
- python Tab自动补全命令设置
- 4. Median of Two Sorted Arrays leetcode python New season for 2016
- 【python】多个文件共用日志系统的重复打印问题
- C#中通过Process运行Python脚本
- leetcode之Binary Tree Paths
- Python 1.5 循环
- leetcode之Sum Root to Leaf Numbers
- 修改ubuntu的默认python版本