Leetcode 386. 字典序排数 C++

    技术2024-07-27  72

    Leetcode 386. 字典序排数

    题目

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

    测试样例

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

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

    题解

    dfs深搜 除了第一位可以用1~9,其余位均为0 ~ 9。详细过程见代码

    代码

    vector<int> ans; void dfs(int now,int n){ ans.push_back(now); for(int i=0; i<=9; i++){ if(now*10+i <= n){ dfs(now*10+i,n); }else break; } } vector<int> lexicalOrder(int n) { for(int i=1; i<=9; i++) if(i<=n) dfs(i,n); return ans; }

    来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/lexicographical-numbers 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

    Processed: 0.011, SQL: 9