首页 > 其他 > 详细

leetcode 字典序排数

时间:2020-02-25 21:53:35      阅读:67      评论:0      收藏:0      [点我收藏+]

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

例如,

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

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

题解:

水题。爆搜。

参考代码:

技术分享图片
 1 class Solution {
 2 public:
 3     void dfs(int n,int res,vector<int>&ans)
 4     {
 5         if(res) ans.push_back(res);
 6         for(int i=0;i<=9;++i)
 7         {
 8             if(res*10+i<=n && res*10+i!=0) 
 9                 dfs(n,res*10+i,ans);
10         }
11     }
12 
13     vector<int> lexicalOrder(int n) 
14     {
15         if(n==0) return {};
16         vector<int> ans;
17         dfs(n,0,ans);
18         return ans;
19     }
20 };
C++

 

leetcode 字典序排数

原文:https://www.cnblogs.com/csushl/p/12363986.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!