386. 字典序排数

阅读 47

2022-02-14

字典序特点:先比对首位,在比对第二位,依次类推。所以第一位先填1,在判断下一位是否大于n,如果小于就递归。

class Solution {
public:
    void solve(vector<int> &ans, const int n, int now) {
        if (now <= n)
            ans.push_back(now);
        for (int i = 0; i < 10; ++i) {
            const int tmp = now * 10 + i;
            if (tmp <= n)
                solve(ans, n, tmp);
        }
    }
    vector<int> lexicalOrder(int n) {
        vector<int> ans;
        for (int i = 1; i <= 9; i++)
            solve(ans, n, i);
        return ans;
    }
};

精彩评论(0)

0 0 举报