leetcode 字典序排數

給定一個整數 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++

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章