Given an integer n, return 1 - n in lexicographical order.
For example, given 13, return: [1,10,11,12,13,2,3,4,5,6,7,8,9].
Please optimize your algorithm to use less time and space. The input size may be as large as 5,000,000.
----------------------------------------------------------------------------------------------------------------------------------------
Solution:
If you could find it's a tree with no more than 10 children. You're on the right way.
Recursive DFS:
class Solution:
def dfs(self, num, n, res):
if (num > n):
return
res.append(num)
for i in range(10):
self.dfs(num*10+i, n, res)
def lexicalOrder(self, n):
res = []
for i in range(1, 10):
self.dfs(i, n, res)
return res
None Recursive DFS (simulate stack):
class Solution:
def lexicalOrder(self, n):
res, sta = [], []
i,cur = 0,1
while (i < n or sta):
while (cur <= n):
res.append(cur)
sta.append(cur)
i += 1
cur *= 10
if (sta):
cur = sta.pop()
if (cur % 10 != 9):
cur += 1
else:
cur = n+1
return res
Non Recursive DFS (copy from leetcode):
class Solution(object):
def lexicalOrder(self, n):
ans = [1]
while len(ans) < n:
new = ans[-1] * 10
while new > n:
new /= 10
new += 1
while new % 10 == 0: # deal with case like 199+1=200 when we need to restart from 2.
new /= 10
ans.append(new)
return ans
Simulate Trie (but going to father looks difficult, copy from leetcode):
class Solution(object):
def lexicalOrder(self, n):
"""
:type n: int
:rtype: List[int]
"""
start = '1'
ans = []
x = n
while x:
int_n = int(start)
if int_n <= n:
ans.append(int_n)
x -= 1
start = start + '0'
else:
while start:
start = start[:-1]
last_digit = int(start[-1])
if last_digit < 9:
start = start[:-1] + str(last_digit + 1)
break
return ans