【Leetcode】【python】Combinations
来源:互联网 发布:手写情书软件 编辑:程序博客网 时间:2024/05/21 18:36
题目大意
求在1到n个数中挑选k个数的所有的组合类型。
解题思路
DFS(回溯法)
代码
直接用数字做
看图,摆明了不让我们这么做么,这最后一个数据集坑死了多少人。
class Solution(object): def combine(self, n, k): """ :type n: int :type k: int :rtype: List[List[int]] """ self.result = [] temp = [] self.combineHelper(n, k, 0, 1, temp) return self.result def combineHelper(self, n, k, length, num_now, temp): # print 'start', temp, list_num, length, self.k if length == k: # print 'add', temp self.result.append(temp[:]) # 这里直接写temp,就会导致result内的temp永远是一个实例,后面修改temp会使得result一直在变化 # print 'result', self.result return for i in range(num_now, n+1): temp.append(i) self.combineHelper(n, k, length+1, i+1, temp) temp.pop()
转为list做
最后一个测试集TLE
class Solution(object): def combine(self, n, k): """ :type n: int :type k: int :rtype: List[List[int]] """ self.k = k self.result = [] list_num = [i for i in range(1, n+1)] self.combineHelper(0, [], list_num) return self.result def combineHelper(self, length, temp, list_num): # print 'start', temp, list_num, length, self.k if length == self.k: # print 'add', temp self.result.append(temp[:]) # 这里直接写temp,就会导致result内的temp永远是一个实例,后面修改temp会使得result一直在变化 # print 'result', self.result return for i, num in enumerate(list_num): temp.append(num) # print temp, list_num[i+1:] # print '-------' self.combineHelper(length+1, temp, list_num[i+1:]) temp.pop()
总结
做DFS时,有很多小细节,比如该题,temp需要pop,不能在上面加入result那里做,应该是在调用递归后做。
此题肯定有非递归写法,有空琢磨。
阅读全文
0 0
- 【LeetCode with Python】 Combinations
- 【LEETCODE】77-Combinations [Python]
- 【Leetcode】【python】Combinations
- LeetCode 77 Combinations (Python详解及实现)
- LeetCode: Combinations
- LeetCode: Combinations
- LeetCode Combinations
- [Leetcode] Combinations
- [LeetCode] Combinations
- Leetcode: Combinations
- LeetCode Combinations
- [Leetcode] Combinations
- [Leetcode] Combinations
- [leetcode] Combinations
- [LeetCode]Combinations
- [leetcode]Combinations
- LeetCode-Combinations
- [leetcode] Combinations
- 普及组初赛总结
- 一篇很全的freemarker教程(摘抄)
- 网易2018校招内推编程题 小易喜欢的数列
- Precision&&Recall&&F1
- 熊猫TV王者荣耀主播人气TOP10
- 【Leetcode】【python】Combinations
- 欢迎使用CSDN-markdown编辑器
- C语言(二)--数据类型
- Bow
- C语言(三)--运算符与表达式
- 2、单例模式(内部类的实现方式)
- C语言(四)--格式输出说明符含义
- LED灯驱动
- C语言(五)--语句