标签:字典 i++ div 迭代 顺序 graph 解法 else bsp
按字典顺序输出1-n
class Solution { public: vector<int> lexicalOrder(int n) { vector<int> res; for(int j=1;j<=9;++j){ helper(res,n,j); } return res; } void helper(vector<int>& res,int n, int j){ if(j>n) return; if(j<=n) res.push_back(j); for(int i=0;i<=9;++i){ helper(res,n,j*10+i); } } };
迭代解法
class Solution { public: vector<int> lexicalOrder(int n) { vector<int> res; int cur=1; for(int i=1;i<=n;i++){ res.push_back(cur); if(cur*10<=n){ cur*=10; }else{ if(cur>=n) cur/=10; cur+=1; while(cur%10==0) cur/=10; } } return res; } };
标签:字典 i++ div 迭代 顺序 graph 解法 else bsp
原文地址:https://www.cnblogs.com/learning-c/p/9740389.html