【剑指Offer-17】打印从1到最大的n位数

问题

输入数字 n,按顺序打印出从 1 到最大的 n 位十进制数。比如输入 3,则打印出 1、2、3 一直到最大的 3 位数 999。要注意大数问题,即输出字符串。

示例

输入: n = 1
输出: [1,2,3,4,5,6,7,8,9]

解答

class Solution {
public:
    string printNumbers(int n) {
        for (int i = 0; i < n; i++) // digit位遍历
            for (int j = 1; j <= 9; j++) { // 首位1~9遍历
                string ans = to_string(j); // 创建首位
                dfs(ans, i, 0);
            }
        return res;
    }
private:
    string res, loop = "0123456789";
    void dfs(string& ans, int digit, int pos) {
        if (pos == digit) {
            res += ans;
            return;
        }
        for (char ch : loop) {
            ans += ch;
            dfs(ans, digit, pos + 1);
            ans.pop_back();
        }
    }
};

重点思路

本题因为要注意大数问题。这个大数包括现有的数据类型都无法存储的数,所以要通过生成字符串解决。本题可以看做每位数字从0到9的全排列,首位为特殊情况,不能为0,所以我们将首位的生成拿到dfs函数外,而dfs函数用于生成除首位外的其他数字。

posted @ 2021-03-10 16:07  tmpUser  阅读(40)  评论(0编辑  收藏  举报