当前位置:网站首页>使用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
边栏推荐
- Huawei machine test question -- deformation of hj53 Yang Hui triangle
- C# WPF UI框架MahApps切换主题
- Niuke white moon race 5 [problem solving mathematics field]
- C# 读写二进制文件
- AOT和单文件发布对程序性能的影响
- Chapter V project quality management of information system project manager summary
- [Euler plan question 13] sum of large numbers
- JS using the parameters of art template
- Depth deterministic strategy gradient (ddpg)
- Chapter VI project information management system summary
猜你喜欢

BLDC double closed loop (speed PI + current PI) Simulink simulation model

Xamarin效果第二十二篇之录音效果

TP5 inherits base and uses the variables in base

MAUI初体验:爽

Detailed explanation of distributed things

Kubernetes - Introduction to actual combat

Some problems encountered in setting Django pure interface, channel and MySQL on the pagoda panel

Sonic cloud real machine tutorial

LNMP MySQL allows remote access

微软是如何解决 PC 端程序多开问题的——内部实现
随机推荐
Cloud computing learning 1 - openstack cloud computing installation and deployment steps with pictures and texts (Xiandian 2.2)
Linux redis - redis database caching service
Blazor University (11)组件 — 替换子组件的属性
樹莓派開發筆記(十二):入手研華ADVANTECH工控樹莓派UNO-220套件(一):介紹和運行系統
How to write the expected salary on your resume to double your salary during the interview?
HLS / chisel practice CORDIC high performance computing complex square root
使用两种方法来解决“最大回文数乘积”问题
Deep q-network (dqn)
Résumé du gestionnaire de projet du système d'information Chapitre VI gestion des ressources humaines du projet
ASP.NET 6 中间件系列 - 自定义中间件类
[learn junit5 from official documents] [II] [writingtests] [learning notes]
Shell learning notes -- shell processing of output stream awk
[ncnn] - the meaning of - 23300 in param
SQL statement - DDL
The space between the left and right of the movie ticket seats is empty and cannot be selected
Wepy learning record
.Net Core 限流控制-AspNetCoreRateLimit
Q-Learning & Sarsa
C# WPF UI框架MahApps切换主题
Winsock programming interface experiment: implementation of ipconfig