Using DFS to solve the "lexicographical sort" problem

Sixteen, lexicographical sorting

16.1. Requirements for title design

  Given an integer n, return all integers in the range [1, n] lexicographically.

  You have to design an algorithm that is O(n) and uses O(1) extra space.

示例 1:
输入:n = 13
输出:[1,10,11,12,13,2,3,4,5,6,7,8,9]

示例 2:
输入:n = 2
输出:[1,2]

提示:
1 <= n <= 5 * 10^4

Source: LeetCode
Link: https://leetcode-cn.com/problems/lexicographical-numbers

16.2. Problem solving ideas

  First, take the numbers from 1 to 9 for cur, and then compare them with n in turn. If n is greater than or equal to the number represented by cur, add cur to res, and then compare the numbers with cur as tens, hundreds, etc. with n Compare, if it is less than or equal to n, continue to add it to res, and finally output it.

16.3. Algorithms

class Solution {
    
    
    List<Integer> res;

    public List<Integer> lexicalOrder(int n) {
    
    
        res = new ArrayList<>();
        for (int i = 1; i <= 9; i++) {
    
    
            dfs(i , n);
        }
        return res;
    }

    //cur当前位
    public void dfs(int cur,int n){
    
    
        //不符合条件
        if (cur > n){
    
    
            return;
        }
        //将符合条件的添加到res中
        res.add(cur);
        //将以cur为十位,百位等的数字比较并添加
        for (int i = 0; i <= 9; i++) {
    
    
            int nextNum = cur * 10 + i;
            if (nextNum > n){
    
    
                break;
            }
            //如果nextNum还小于n,再进行一次dfs
            dfs(nextNum,n);
        }
    }
}

Reference video: B station up master Guo Guo wg

Guess you like

Origin blog.csdn.net/qq_52916408/article/details/124240951