当前位置:网站首页>剑指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
边栏推荐
猜你喜欢

Error in go mode tidy go warning “all” matched no packages

Huawei's "genius boy" Zhihui Jun has made a new work, creating a "customized" smart keyboard from scratch

297. 二叉树的序列化与反序列化

SWM32 Series Tutorial 6 - Systick and PWM

调度中心xxl-Job

IOT cross-platform component design scheme

ShardingSphere之读写分离(八)

Detailed explanation of 9 common reasons for MySQL index failure

【Demo】ABAP Base64加解密测试

typescript9 - common base types
随机推荐
无线模块的参数介绍和选型要点
MySQL的触发器
MySQL系列一:账号管理与引擎
This project is so geeky
mysql主从复制及读写分离脚本-亲测可用
typescript9-常用基础类型
什么是Promise?Promise的原理是什么?Promise怎么用?
typescript17 - function optional parameters
Oracle has a weird temporary table space shortage problem
图像处理工具设计
MySQL database advanced articles
Why use high-defense CDN when financial, government and enterprises are attacked?
Summary of MySQL database interview questions (2022 latest version)
87. 把字符串转换成整数
MySQL table design for message queue to store message data
ECCV 2022丨轻量级模型架构火了,力压苹果MobileViT(附代码和论文下载)
分布式.分布式锁
ShardingSphere's public table combat (7)
【Yugong Series】July 2022 Go Teaching Course 017-IF of Branch Structure
Typescript18 - object type