Leetcode Lexicographical Numbers 数字字典序列输出

231 篇文章 0 订阅

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

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值