Dictionary ordinal number rows leetcode

Given an integer n, returns the dictionary in order from 1 to n.

E.g,

Given n = 1 3, returns [1,10,11,12,13,2,3,4,5,6,7,8,9].

Please optimization algorithm time as possible complexity and space complexity. N is equal to the input data is less than 5,000,000.

answer:

Water problem. Burst search.

Reference Code:

 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++

 

Guess you like

Origin www.cnblogs.com/csushl/p/12363986.html