当前位置:网站首页>剑指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
边栏推荐
- typescript18-对象类型
- 埃拉托斯特尼筛法
- In Google Cloud API gateway APISIX T2A and T2D performance test
- 【愚公系列】2022年07月 Go教学课程 016-运算符之逻辑运算符和其他运算符
- mysql索引失效的常见9种原因详解
- 无线模块的参数介绍和选型要点
- WEB Security Basics - - - Vulnerability Scanner
- MySQL database (basic)
- How to Add a Navigation Menu on Your WordPress Site
- 【愚公系列】2022年07月 Go教学课程 017-分支结构之IF
猜你喜欢
随机推荐
Redis learning
XSS related knowledge
typescript9 - common base types
[Yugong Series] July 2022 Go Teaching Course 016-Logical Operators and Other Operators of Operators
Can deep learning solve the parameters of a specific function?
ShardingSphere之水平分库实战(四)
深度学习可以求解特定函数的参数么?
Unity2D horizontal version game tutorial 4 - item collection and physical materials
typescript13-类型别名
ShardingSphere之读写分离(八)
typescript13 - type aliases
【愚公系列】2022年07月 Go教学课程 019-循环结构之for
DOM系列之 client 系列
ShardingSphere's unsharded table configuration combat (6)
24. 请你谈谈单例模式的优缺点,注意事项,使用场景
typescript15-(同时指定参数和返回值类型)
DOM系列之动画函数封装
ros2知识:在单个进程中布置多个节点
[Tang Yudi Deep Learning-3D Point Cloud Combat Series] Study Notes
【952. Calculate the maximum component size according to the common factor】









