题目链接

字典序排数

题目描述

image.png

实现代码

字典序概念:按照字符串比较的形式进行排序,从前往后每个位置的数字的ASCII编码进行比较

DFS算法思想:start=1,从start开始进行深度递归遍历,每次乘以10,如果小于等于n,则添加到结果列表中;如果大于n,则回到上一步start进行自增1,再按照前面的步骤进行DFS遍历,直到n个数全部字典序排列;

实现代码:

  1. class Solution {
  2. public List<Integer> lexicalOrder(int n) {
  3. int start = 1;
  4. List<Integer> resultList = new ArrayList();
  5. for(int i=1; i<=n; i++) {
  6. resultList.add(start);
  7. if(start * 10 <= n) {
  8. start *= 10;
  9. } else {
  10. while(start+1 > n || start % 10 == 9) {
  11. start /= 10;
  12. }
  13. start++;
  14. }
  15. }
  16. return resultList;
  17. }
  18. }