当前位置:网站首页>剑指offer17---打印从1到最大的n位数
剑指offer17---打印从1到最大的n位数
2022-07-31 00:55:00 【星光技术人】
打印从1到最大的n位数

题目考点:原题设定数组再INT32的范围内,所以可以直接使用for循环依次求出;但是如果数值超过INT32,就需要使用long型;如果数字比long更大怎么办;无论是 short / int / long … 任意变量类型,数字的取值范围都是有限的。因此,大数的表示应用字符串 String 类型

- 递归求解1
#include<iostream>
#include<vector>
#include<queue>
using namespace std;
class Solution {
public:
string path = "";
vector<string> res;
vector<char> strs = {
'0','1','2','3','4','5','6','7','8','9'};
void printNums(int n)
{
dfs(0, n);
for (auto str : res)
cout << str << endl;
return;
}
void dfs(int idx, int n)
{
if (path.size() == n)
{
res.push_back(path);
return;
}
for (int i =0; i <= 9; i++)
{
path.push_back(strs[i]);
dfs(i, n);
path.pop_back();
}
}
};
int main()
{
Solution S;
S.printNums(2);
return 0;
}
00
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
- 递归解法2
#include<iostream>
#include<vector>
#include<queue>
using namespace std;
class Solution {
public:
string path = "";
vector<string> res;
vector<char> strs = {
'0','1','2','3','4','5','6','7','8','9'};
void printNums(int n)
{
res = {
"1","2","3","4","5","6","7","8","9" };
dfs(0, n);
for (auto str : res)
cout << str << endl;
return;
}
//添加第idx个数字,目标长度为n
void dfs(int idx, int n)
{
if (idx==n)
{
res.push_back(path);
return;
}
//第一个数字不能为0
int start = idx == 0 ? 1 : 0;
for (int i =start; i <= 9; i++)
{
path.push_back(strs[i]);
dfs(idx + 1, n);
path.pop_back();
}
}
};
int main()
{
Solution S;
S.printNums(2);
return 0;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
边栏推荐
- DOM系列之动画函数封装
- Thesis understanding: "Designing and training of a dual CNN for image denoising"
- Preparations for web vulnerabilities
- 不用Swagger,那我用啥?
- 分布式.幂等性
- How to Add a Navigation Menu on Your WordPress Site
- Oracle has a weird temporary table space shortage problem
- 【Demo】ABAP Base64加解密测试
- typescript15-(同时指定参数和返回值类型)
- Responsive layout vs px/em/rem
猜你喜欢
随机推荐
24. Please talk about the advantages and disadvantages of the singleton pattern, precautions, usage scenarios
人工智能与云安全
ELK部署脚本---亲测可用
typescript11 - data types
What is Promise?What is the principle of Promise?How to use Promises?
华为“天才少年”稚晖君又出新作,从零开始造“客制化”智能键盘
typescript17 - function optional parameters
Huawei's "genius boy" Zhihui Jun has made a new work, creating a "customized" smart keyboard from scratch
[Tang Yudi Deep Learning-3D Point Cloud Combat Series] Study Notes
Basic usage of async functions and await expressions in ES6
MySql data recovery method personal summary
822. 走方格
Detailed explanation of 9 common reasons for MySQL index failure
MySQL筑基篇之增删改查
【Yugong Series】July 2022 Go Teaching Course 013-Constants, Pointers
Go study notes (84) - Go project directory structure
Why use high-defense CDN when financial, government and enterprises are attacked?
分布式.分布式锁
go mode tidy出现报错go warning “all“ matched no packages
typescript12 - union types









