LeetCode - 386. Lexicographical Numbers
Given an integer n, return 1 - n in lexicographical order.
For example, given 13, return: [1,10,11,12,13,2,3,4,5,6,7,8,9].
Please optimize your algorithm to use less time and space. The input size may be as large as 5,000,000.
按字典序求所给范围数字列表
回溯,dfs
class Solution { List<Integer> res; public List<Integer> lexicalOrder(int n) { res = new ArrayList<>(); for (int i=1; i<10; i++) { if (i > n) break; dfs(n, i); } return res; } public void dfs(int n, int cur) { if (cur > n) return; res.add(cur); for (int i=0; i<10; i++) { int next = cur * 10 + i; if (next > n) return; dfs(n, next); } } }
作者:Pickle
声明:对于转载分享我是没有意见的,出于对博客园社区和作者的尊重一定要保留原文地址哈。
致读者:坚持写博客不容易,写高质量博客更难,我也在不断的学习和进步,希望和所有同路人一道用技术来改变生活。觉得有点用就点个赞哈。








浙公网安备 33010602011771号