欢迎访问 生活随笔!

生活随笔

当前位置: 首页 > 编程语言 > java >内容正文

java

leetcode 386. Lexicographical Numbers | 386. 字典序排数(Java)

发布时间:2024/2/28 java 32 豆豆
生活随笔 收集整理的这篇文章主要介绍了 leetcode 386. Lexicographical Numbers | 386. 字典序排数(Java) 小编觉得挺不错的,现在分享给大家,帮大家做个参考.

题目

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

题解

思路:先序遍历 10 叉树,参考:Simple Java DFS Solution

The idea is pretty simple. If we look at the order we can find out we just keep adding digit from 0 to 9 to every digit and make it a tree. Then we visit every node in pre-order. 1 2 3 .../\ /\ /\10 ...19 20...29 30...39 .... class Solution {public List<Integer> lexicalOrder(int n) {ArrayList<Integer> res = new ArrayList<>();for (int i = 1; i < 10; i++) {dfs(i, n, res);}return res;}public void dfs(int num, int max, List<Integer> list) {if (num > max) return;list.add(num);for (int i = 0; i < 10; i++) {if (num * 10 + i > max) return;dfs(num * 10 + i, max, list);}} }

总结

以上是生活随笔为你收集整理的leetcode 386. Lexicographical Numbers | 386. 字典序排数(Java)的全部内容,希望文章能够帮你解决所遇到的问题。

如果觉得生活随笔网站内容还不错,欢迎将生活随笔推荐给好友。