题目分析:[[EVD]] - 剑指 Offer 17. 打印从1到最大的n位数
https://leetcode-cn.com/problems/da-yin-cong-1dao-zui-da-de-nwei-shu-lcof/
简单描述:
- 输入数字 n,按顺序打印出从 1 到最大的 n 位十进制数。比如输入 3,则打印出 1、2、3 一直到最大的 3 位数 999。
限制🚫
- 用返回一个整数列表来代替打印
- n 为正整数
示例:
输入: n = 1
输出: [1,2,3,4,5,6,7,8,9]
解题思路:
思路:
- 题目提供的函数返回为int,不扩展开来考虑大数的话,直接输出
- #字符串 考虑大数的话,使用字符串操作,最关键的是去掉高位多余的0
效率:
- 时间复杂度
- 空间复杂度
代码:
- 1.不考虑大数
class Solution
{
public:
/*不考虑大数*/
vector<int> printNumbers(int n)
{
int end = pow(10, n) - 1;
vector<int> res;
for (int i = 1; i <= end; i++)
res.push_back(i);
return res;
}
};
- 2.考虑大数
class Solution
{
private:
string res = "";
vector<int> re; // 针对本题设定返回
char loop[10] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9'};
int s, jinwei = 0;
void dfs(int i, string c, int len)
{
if (i == len)
{
c = c.substr(s, len - s);
if (c != "0")
{
res.append(c + ',');
re.push_back(atoi(c.c_str())); //针对本题设定返回
}
if (len - s == jinwei)
s--;
return;
}
for (auto ch : loop)
{
if (ch == '9')
jinwei++;
dfs(i + 1, c + ch, len);
}
jinwei--;
}
public:
/*考虑大数*/
vector<int> printNumbers(int n)
{
s = n - 1; // 初始时1-9,舍去前面的n-1个0
dfs(0, "", n);
res.erase(res.end() - 1);
return re;
}
};