-
题目链接 https://leetcode-cn.com/problems/lexicographical-numbers/submissions/
-
题目描述
- 给定一个整数 n, 返回从 1 到 n 的字典顺序。
- 给定 n =1 3,返回 [1,10,11,12,13,2,3,4,5,6,7,8,9] 。
-
解题思路
- 排序: 将数组元素转换成字符串然后排序
- DFS:递归公式为
-
代码
- python(排序)
class Solution: def lexicalOrder(self, n: int) -> List[int]: return sorted([i for i in range(1, n+1)], key=str)
- python(回溯)
class Solution: def lexicalOrder(self, n: int) -> List[int]: ans = [] def _dfs(a): nonlocal ans if a > n:return ans.append(a) for i in range(0, 10): _dfs(a * 10 + i) for i in range(1, 10): _dfs(i) return ans
- python(排序)
leetcode 386. 字典序排数
最新推荐文章于 2022-04-21 19:53:03 发布