LeetCode 386. Lexicographical Numbers - 前缀树(Trie Tree or Prefix Tree)系列题10

Given an integer n, return all the numbers in the range [1, n] sorted in lexicographical order.

You must write an algorithm that runs in O(n) time and uses O(1) extra space. 

Example 1:

Input: n = 13
Output: [1,10,11,12,13,2,3,4,5,6,7,8,9]

Example 2:

Input: n = 2
Output: [1,2]

Constraints:

  • 1 <= n <= 5 * 104

这题看起来不太像可以用前缀树(Trie)来解答,但题目的关键字“字典序lexicographical“”却是前缀树的一个特性,前缀树从根顶点开始从上到下从左到右刚好是按字典序排序的。

解题思路:

把从1到n的数转化成字符串,用标准的前缀树插入函数把数字字符串按字符插入前缀树里,另外在每个节点把对应的数字存下来方便后面遍历时读取。

从上到下从左到右遍历整棵前缀树,把遇到的每个节点的数字取出放入答案中。

class TrieNode:
    def __init__(self):
        self.num = 0
        self.children = [None] * 10
        
class Solution:
    def lexicalOrder(self, n: int) -> List[int]:
        root = TrieNode()
        
        for i in range(1,n + 1):
            self.insert(root, i)
            
        res = []
        self.search(root, res)
        return res
        
    def insert(self, root, i):
        s = str(i)
        node = root
        for c in s:
            idx = int(c)
            if not node.children[idx]:
                node.children[idx] = TrieNode()
            node = node.children[idx]
        node.num = i
            
    def search(self, root, ans):
        if root.num > 0:
            ans.append(root.num)
        
        for i in range(10):
            if not root.children[i]:
                continue
            self.search(root.children[i], ans)

注:这题要求空间复杂度为O(1),很显然用了前缀树就到不到满足要求,但也不失为一题好的前缀树Trie练习题。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值