【LeetCode-递归】字典序排数

题目描述

给定一个整数 n, 返回从 1 到 n 的字典顺序。

例如,

给定 n =1 3,返回 [1,10,11,12,13,2,3,4,5,6,7,8,9] 。

请尽可能的优化算法的时间复杂度和空间复杂度。 输入的数据 n 小于等于 5,000,000。

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

思路1

定义比较函数,然后对数组进行排序。

class Solution {
public:
    static bool cmp(int a, int b){
        return to_string(a)<to_string(b);
    }
    vector<int> lexicalOrder(int n) {
        vector<int> ans;
        for(int i=1; i<=n; i++) ans.push_back(i);
        sort(ans.begin(), ans.end(), cmp);
        return ans;
    }
};
  • 时间复杂度:O(nlogn)
  • 空间复杂度:O(n)

思路2

使用递归来做。递归的过程就是在一棵 10 叉树上进行先序遍历。代码如下:

class Solution {
public:
    vector<int> lexicalOrder(int n) {
        vector<int> ans;
        dfs(n, 0, ans);
        return ans;
    }

    void dfs(int n, int curNum, vector<int>& ans){
        if(curNum>n) return;
        if(curNum!=0) ans.push_back(curNum);

        for(int i=0; i<=9; i++){
            if(curNum*10+i>0){
                dfs(n, curNum*10+i, ans);
            }
        }
    }
};
原文地址:https://www.cnblogs.com/flix/p/13495271.html