Lexicographical Numbers
来源:互联网 发布:扫描服务器开放的端口 编辑:程序博客网 时间:2024/06/01 09:23
leetcode第386题,按照字典序排列数字。
这个题要求尽量降低时间复杂度和空间复杂度,利用python的黑魔法一开始想这样做。先生成数字序列,并把它们字符串化,然后排序,在利用map转换回数字列表形式。
def lexicalOrder(n): numstr = [str(i) for i in xrange(1,n+1)] numstr.sort() return list(map(int,numstr))
这样做时间上还是很快的,但是提交会发现内存爆掉了。。。
后来发现可以使用dfs,而且思路很巧妙。注意这里按照字典序,就是不断向下递归的过程。首先先找到开头是1的,然后乘10在加上1-10,递归的出口就是加入最终结果列表的数字不要大于指定的n。
class Solution(object): def lexicalOrder(self, n): """ :type n: int :rtype: List[int] """ def dfs(num,res): if num <= n: res.append(num) t = num*10 if t <= n: for i in range(10): dfs(t+i,res) res = [] for i in range(1,10): dfs(i,res) return res
0 0
- Lexicographical Numbers
- Lexicographical Numbers
- Lexicographical Numbers
- Lexicographical Numbers
- Lexicographical Numbers
- 386. Lexicographical Numbers
- LeetCode 386 Lexicographical Numbers
- [leetcode] 386. Lexicographical Numbers
- leetcode---Lexicographical Numbers
- leetcode:Lexicographical Numbers
- [leetcode]386. Lexicographical Numbers
- 【Leetcode】386. Lexicographical Numbers
- [Leetcode]386. Lexicographical Numbers
- 386. Lexicographical Numbers
- 386. Lexicographical Numbers
- LeetCode 386. Lexicographical Numbers
- 386. Lexicographical Numbers
- 386. Lexicographical Numbers
- jQuery 事件方法
- Fastcv——机器学习SVM初识
- 数据库查询父分类与子分类
- HDU 5873 Football Games(Landau定理)
- python编码 2016.09.18回顾
- Lexicographical Numbers
- JavaScript 中函数自运行
- 最短路径算法--无权最短路径
- Oracle expdp/impdp详解
- 将VC++6.0项目转换为VS2010项目时遇到的问题与解决方法
- leetcode 49. Group Anagrams
- 预定义着色器预处理宏
- 数据结构与算法分析——Java语言描述
- AIDL简单使用