方法一:不考虑大数溢出:时间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)
题解:
- 考虑大数溢出则需要借助字符串来统计每个数字
- 每个数其实就是0~9的排列组合,因此递归每位的组合,满足组合条件时插入数组
- 为了通过题目的测试,插入之前用 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;
}
};