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

本文介绍了两种方法来处理大数打印问题,分别是在不考虑大数溢出的情况下直接使用整型数组,以及考虑大数溢出时采用递归和字符串处理。这两种方法的时间复杂度均为O(10^n),但空间复杂度不同,第一种为O(1),第二种为O(10^n)。通过这两种方式,可以有效地生成并打印出从1到10^n的所有整数。
摘要由CSDN通过智能技术生成

方法一:不考虑大数溢出:时间O( 1 0 n 10^n 10n),空间O(1)

题解:不考虑大数溢出 int 的情况

class Solution {
public:
    vector<int> printNumbers(int n) 
    {
        int count = pow(10, n);
        vector<int> res(count - 1);
        for (int i = 1; i < count; i++)
        {
            res[i - 1] = i;
        }
        return res;
    }
};

方法二:大数打印:时间O( 1 0 n 10^n 10n),空间O( 1 0 n 10^n 10n)

题解:

  1. 考虑大数溢出则需要借助字符串来统计每个数字
  2. 每个数其实就是0~9的排列组合,因此递归每位的组合,满足组合条件时插入数组
  3. 为了通过题目的测试,插入之前用 stoi 把数字转换整型
class Solution {
public:
   vector<int> res;
vector<char> board = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9' };
void dfs(int index, int n, string& str)
{
    if (index == n)
    {
        int tmp = stoi(str);
        if (tmp != 0)
            res.push_back(tmp);
        return;
    }
    for (int i = 0; i < board.size(); i++)
    {
        str.push_back(board[i]);
        dfs(index + 1, n, str);
        str.pop_back();
    }
}
vector<int> printNumbers(int n)
{
    string str;
    dfs(0, n, str);
    return res;
}
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值