386. Lexicographical Numbers

按字典顺序输出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;
    }
};

 

posted @ 2018-10-03 18:29  hopskin1  阅读(93)  评论(0编辑  收藏  举报