其他分享
首页 > 其他分享> > 字典序排数( dfs)

字典序排数( dfs)

作者:互联网

题目连接:

https://leetcode-cn.com/problems/lexicographical-numbers/

题目大意:

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

例如,

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

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

具体思路:

dfs,确定好开头,每一次把当前的开头走完。

AC代码:

 1 class Solution {
 2 public:
 3     vector<int> lexicalOrder(int n) {
 4      vector<int>ans;
 5      for( int i= 1 ;i <=9 ;i++){
 6         dfs( i , n ,ans);
 7      }
 8     return ans;
 9     }
10     void dfs(int u , int top,vector<int>&ans){
11     if( u > top )return ;
12     ans.push_back(u);
13     for( int i =0 ; i < 10 ;i++ ){
14       if(u*10 + i > top) break;
15       else
16       dfs(u*10 + i,top, ans);
17   }
18     }
19 };

 

标签:10,排数,int,top,dfs,ans,复杂度,字典
来源: https://www.cnblogs.com/letlifestop/p/11197694.html