2022-4-18 每日一题-leetcode

题目链接:https://leetcode-cn.com/problems/lexicographical-numbers/

 

个人题解:

  • 我们用一个 $tire$ 树来表示所有的数,如果当前数是在 $1-n$ 范围内的,就插入到答案中。因为表示了所有数,所以没必要模拟一个 $tire$ 数并且插入。
  • 所以我们只需要模拟一个在 $trie$ 上树搜索即可。
  • 时间复杂度 $O(n)$

代码:

class Solution {
public:
    vector<int> res;

    vector<int> lexicalOrder(int n) {
        for(int i=1;i<=9;i++) dfs(i,n);
        return res;
    }

    void dfs(int u,int n){
        if(u>n) return;
        res.push_back(u);
        for(int i=0;i<=9;i++) dfs(u*10+i,n);
    }
};

image

posted @ 2022-04-18 07:17  黑VS白-清墨  阅读(22)  评论(0)    收藏  举报