leetcode-386:字典序排数

简介: leetcode-386:字典序排数

题目

题目连接

给你一个整数 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 Trie{
public:
    bool isEnd=false;
    vector<Trie*> next=vector<Trie*>(10,nullptr);
};
class Solution {
public:
    Trie* trie=new Trie();
    vector<int> res;
    vector<int> lexicalOrder(int n) {
        for(int i=1;i<=n;i++){
            insert(to_string(i));
        }
        traversal(trie,0);
        return res;
    }
    //字典树前序遍历
    void traversal(Trie* root,int path){
        if(root->isEnd){
            res.push_back(path);
        }
        for(int i=0;i<10;i++){
            if(root->next[i]){
                traversal(root->next[i],path*10+i);
            }
        }
    }
    //字典树插入节点
    void insert(string&& s){
        Trie* node=trie;
        for(char c:s){
            if(node->next[c-'0']==nullptr){
                node->next[c-'0']=new Trie();
            }
            node=node->next[c-'0'];
        }
        node->isEnd=true;
    }
};

方法二:迭代

class Solution {
public:
    vector<int> lexicalOrder(int n) {
        vector<int> res(n);
        int num=1;
        for(int i=0;i<n;i++){
            res[i]=num;
            if(num*10<=n){
                num*=10;
            }else{
                while(num%10==9||num+1>n){
                    num/=10;
                }
                num++;
            }
        }
        return res;
    }
};


相关文章
|
2月前
|
存储
全排列问题
全排列问题
11 0
|
11月前
|
算法
LeetCode-386 字典序排数
LeetCode-386 字典序排数
|
2月前
leetcode-1800:最大升序子数组和
leetcode-1800:最大升序子数组和
23 0
|
2月前
面试题 01.04:回文排列
面试题 01.04:回文排列
21 0
|
2月前
leetcode-516:最长回文子序列
leetcode-516:最长回文子序列
23 0
|
算法 C++ Python
每日算法系列【LeetCode 386】字典序排数
每日算法系列【LeetCode 386】字典序排数
|
算法
每日一题——字典序排数
每日一题——字典序排数
51 0
每日一题——字典序排数
leetcode 516 最长回文子序列
leetcode 516 最长回文子序列
67 0
leetcode 516 最长回文子序列
|
机器学习/深度学习 NoSQL Shell
力扣刷题记录——344.反转字符串、345.反转字符串中的元音、349.两个数组的交集
力扣刷题记录——344.反转字符串、345.反转字符串中的元音、349.两个数组的交集
力扣刷题记录——344.反转字符串、345.反转字符串中的元音、349.两个数组的交集