1、题目描述:
2、题解:
方法1:DFS
思路:
对1-10进行DFS,每次DFS,都是找到开头为1-10的数字,且小于n。
1 2 3 ...
/ \ / \ / \
10 ... 19 20 ... 29 30 ... 39
class Solution:
def lexicalOrder(self, n):
if n < 1:
return []
self.n,self.res = n,[]
def dfs(cur):
if cur > self.n:return
self.res.append(cur)
for i in range(10):#遍历0-9
dfs(10*cur+i)
for i in range(1,10): #遍历1-9
dfs(i)
return self.res
方法2:字符串排序:
class Solution:
def lexicalOrder(self, n):
return sorted(range(1,n+1),key = str)
3、复杂度分析:
方法1:
时间复杂度:O(N)
空间复杂度:O(1)
方法2:
时间复杂度:O(NlogN)
空间复杂度:O(1)