one line of code at a time
[leetcode] 386. Lexicographical Numbers 파이썬 코드 본문
https://leetcode.com/problems/lexicographical-numbers
lexicographical order로 정렬하라는 문제다.
예시를 보면 딱 알 수 있다.
n = 13 이면, 정렬된 output은 [1, 10, 11, 12, 13, 2, 3, 4, 5, 6, 7, 8, 9] 이다.
DFS로 풀 수 있다.
이 솔루션의 time complexity는 노드를 한 번씩 방문하니까 O(n)이다.
class Solution(object):
def lexicalOrder(self, n):
res = []
def dfs(curr):
# base case
if curr > n:
return
res.append(curr)
for i in range(10):
dfs(curr * 10 + i)
for i in range(1, 10): # 가장 맨 앞의 숫자
dfs(i)
return res
참고
'leetcode' 카테고리의 다른 글
| [leetcode] 538. Convert BST to Greater Tree / 1038. Binary Search Tree to Greater Sum Tree 파이썬 코드 (1) | 2024.09.26 |
|---|---|
| [leetcode] 143. Reorder List 파이썬 코드 (0) | 2024.09.25 |
| [leetcode] 3043. Find the Length of the Longest Common Prefix 파이썬 코드 (0) | 2024.09.25 |
| [leetcode] 141. Linked List Cycle 파이썬 코드 (0) | 2024.09.25 |
| [leetcode] 841. Keys and Rooms 파이썬 코드 (0) | 2024.09.24 |