当前位置:网站首页>使用DFS来解决“字典序排数”问题
使用DFS来解决“字典序排数”问题
2022-04-23 03:02:00 【&小小白&】
十六、字典序排数
16.1、题设要求
给你一个整数 n ,按字典序返回范围 [1, n] 内所有整数。
你必须设计一个时间复杂度为 O(n) 且使用 O(1) 额外空间的算法。
示例 1:
输入:n = 13
输出:[1,10,11,12,13,2,3,4,5,6,7,8,9]
示例 2:
输入:n = 2
输出:[1,2]
提示:
1 <= n <= 5 * 10^4
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/lexicographical-numbers
16.2、解题思路
先给cur取1到9上面的数字,然后依次与n进行比较,如果n大于等于cur代表的数字,则将cur添加到res中,再将以cur为十位,百位等的数字与n比较,如果小于等于n,则继续添加进res中,最后输出即可.
16.3、算法
class Solution {
List<Integer> res;
public List<Integer> lexicalOrder(int n) {
res = new ArrayList<>();
for (int i = 1; i <= 9; i++) {
dfs(i , n);
}
return res;
}
//cur当前位
public void dfs(int cur,int n){
//不符合条件
if (cur > n){
return;
}
//将符合条件的添加到res中
res.add(cur);
//将以cur为十位,百位等的数字比较并添加
for (int i = 0; i <= 9; i++) {
int nextNum = cur * 10 + i;
if (nextNum > n){
break;
}
//如果nextNum还小于n,再进行一次dfs
dfs(nextNum,n);
}
}
}
参考视频:B站up主郭郭 wg
版权声明
本文为[&小小白&]所创,转载请带上原文链接,感谢
https://blog.csdn.net/qq_52916408/article/details/124240951
边栏推荐
- Cherno_ Game engine series tutorial (5): 101~
- Opencv combines multiple pictures into video
- 最通俗易懂的依赖注入与控制反转
- tf. keras. layers. Embedding function
- 《信息系统项目管理师总结》第四章 项目成本管理
- Shell script learning notes - regular expressions
- C#中元组对象Tuple的使用
- Sonic cloud real machine tutorial
- Processes and threads
- Huawei machine test question -- deformation of hj53 Yang Hui triangle
猜你喜欢
PDH optical transceiver 4-way E1 + 4-way 100M Ethernet 4-way 2m optical transceiver FC single fiber 20km rack type
利用栈的回溯来解决“文件的最长绝对路径”问题
最通俗易懂的依赖注入之生命周期
Kubernetes - Introduction to actual combat
Niuke white moon race 6 [solution]
Traversée de l'arbre L2 - 006
最通俗易懂的依赖注入与控制反转
Response processing of openfeign
Cherno_ Game engine series tutorial (5): 101~
Traversal of l2-006 tree (middle and later order determination binary tree & sequence traversal)
随机推荐
Liunx foundation - zabbix5 0 monitoring system installation and deployment
Publish to NPM?
Numpy append function
Introduction to ACM [inclusion exclusion theorem]
ASP.NET 6 中间件系列 - 执行顺序
Typescript Learning Guide
Redis Cluster集群,主节点故障,主从切换后ip变化,客户端需要处理不
L2-006 樹的遍曆(中後序確定二叉樹&層序遍曆)
L2-006 树的遍历(中后序确定二叉树&层序遍历)
《信息系统项目管理师总结》第五章 项目质量管理
Winsock programming interface experiment: Ping
Small companies don't make formal offers
Centos7 install MySQL 8 0
tf. keras. layers. MaxPooling? D function
Summary of software test interview questions
ele之Table表格的封装
对.NET未来的一点感悟
MYSQL04_ Exercises corresponding to arithmetic, logic, bit, operator and operator
Chapter VII project communication management of information system project manager summary
Cloud computing learning 1 - openstack cloud computing installation and deployment steps with pictures and texts (Xiandian 2.2)