使用DFS来解决“字典序排数”问题

十六、字典序排数

16.1、题设要求

  给你一个整数 n ,按字典序返回范围 [1, n] 内所有整数。

  你必须设计一个时间复杂度为 O(n) 且使用 O(1) 额外空间的算法。

示例 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

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/lexicographical-numbers

16.2、解题思路

  先给cur取1到9上面的数字,然后依次与n进行比较,如果n大于等于cur代表的数字,则将cur添加到res中,再将以cur为十位,百位等的数字与n比较,如果小于等于n,则继续添加进res中,最后输出即可.

16.3、算法

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);
        }
    }
}

参考视频:B站up主郭郭 wg

猜你喜欢

转载自blog.csdn.net/qq_52916408/article/details/124240951