1/20/2021

[LeetCode] 386. Lexicographical Numbers

 Problem : https://leetcode.com/problems/lexicographical-numbers/



class Solution:
    def lexicalOrder(self, n: int) -> List[int]:
        result = []
        
        def backtrack(x):
            if x <= n:
                result.append(x)
            
                for t in range(10):
                    if x * 10 + t <= n:
                        backtrack(x*10 + t)
                    else:
                        break
            
            return result

        result = []
        for x in range(1, 10):
            if x <= n:
                backtrack(x)
        
        return result

No comments:

Post a Comment