386. 字典序排 (模拟 dfs)

难度中等

 

给你一个整数 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]

class Solution:
    def lexicalOrder(self, n: int) -> List[int]:
        prefix = 1
        cnt = 0
        res =[]
        while cnt < n:
            res.append(prefix)
            if prefix*10 <= n: # 先找到子节点,最后一层
                prefix*=10
            else:# 最后一层后,在当层递增,递增到109 or target, 回溯到上一层
                while prefix%10==9 or prefix ==n: prefix //= 10
                prefix+=1
            cnt+=1
        return res

 







class Solution:
    def lexicalOrder(self, n: int) -> List[int]:
        k = len(str(n))
        res = []
        def dfs(path,level):
            if level > k:
                return
            if path != "" and path!='0' and int(path) <= n:
                if str(int(path)) == path:
                    res.append(int(path))

            for i in range(10):
                dfs(path+str(i),level+1)
        dfs("",0)
        return res

 




class Solution {
public:
    vector<int> res;
    void dfs(int cur, int n) {
        if (cur>n) return;
        res.emplace_back(cur);
        for(int i =0;i < 10;i++) {
            dfs(cur*10+i,n);
        }
    }
    vector<int> lexicalOrder(int n) {
        for(int i = 1; i <= 9;i++) {
            dfs(i,n);
        }
        return res;
    }
};

 

 

class Solution {
public:

    vector<int> lexicalOrder(int n) {
        vector<int> path;
        int cnt = 0;
        int prefix = 1;
        while(cnt<n) {
            path.emplace_back(prefix);
            if (prefix*10 <= n) {
                prefix *= 10;
            } else {
                // 回溯到顶层
                // 到199 的时候改回溯到2了, 或者正好等于n=34, prefix ==34,也该停止了,返回4,继续遍历
                while(prefix %10==9 || prefix == n) {
                    prefix /=10;
                }
                prefix++;
            }
            cnt++;
        }
        return path;
    }
};

 

posted @ 2022-06-10 21:21  乐乐章  阅读(26)  评论(0编辑  收藏  举报