Skip to content

Commit 09c7ce3

Browse files
committed
add LeetCode 1291. 顺次数
1 parent d8c5662 commit 09c7ce3

File tree

1 file changed

+94
-0
lines changed

1 file changed

+94
-0
lines changed

Diff for: 递归与回溯/LeetCode 1291. 顺次数.md

+94
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,94 @@
1+
![](https://imgconvert.csdnimg.cn/aHR0cHM6Ly9jZG4uanNkZWxpdnIubmV0L2doL2Nob2NvbGF0ZTE5OTkvY2RuL2ltZy8yMDIwMDgyODE0NTUyMS5qcGc?x-oss-process=image/format,png)
2+
>仰望星空的人,不应该被嘲笑
3+
4+
## 题目描述
5+
6+
我们定义「顺次数」为:每一位上的数字都比前一位上的数字大 1 的整数。
7+
8+
请你返回由 [low, high] 范围内所有顺次数组成的 有序 列表(从小到大排序)。
9+
10+
11+
12+
示例 1:
13+
14+
```css
15+
输出:low = 100, high = 300
16+
输出:[123,234]
17+
```
18+
19+
示例 2:
20+
21+
```css
22+
输出:low = 1000, high = 13000
23+
输出:[1234,2345,3456,4567,5678,6789,12345]
24+
25+
```
26+
27+
提示:
28+
29+
```css
30+
10 <= low <= high <= 10^9
31+
```
32+
33+
来源:力扣(LeetCode)
34+
链接:https://leetcode-cn.com/problems/sequential-digits
35+
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
36+
37+
38+
39+
## 解题思路
40+
「顺次数」为:每一位上的数字都比前一位上的数字大 1 的整数。
41+
42+
也就是例如 `1234`这样的数字,然后给你一段区间确定范围。
43+
44+
官方给了枚举方式,反正数据量也不是很大,但是我觉得还是有很多数字没必要枚举,可以直接剪枝掉。我的做法是先求出最小值和最大值对应字符串的长度,即求出我们能枚举的数字的长度范围。
45+
46+
然后我们的起点的最小值从 `1` 开始,起点的最大值从 `10-len` 开始。为什么是 `10-len`?举例说明,示例1给的是 `[100,300]`范围的值,那么可枚举的长度 `len` 为 3,起点的最大值就位 10 - 3 = 7。那么此时顺次数为 `789` 但是不在我们区间范围内,舍弃。然后`8、9`开头的数字就不需要枚举了。 这样,我们就能剪掉一部门数据了。(虽然暴力是永远滴神...)
47+
48+
```css
49+
/**
50+
* @param {number} low
51+
* @param {number} high
52+
* @return {number[]}
53+
*/
54+
var sequentialDigits = function(low, high) {
55+
let res = []
56+
let lowLen = low.toString().length
57+
let highLen = high.toString().length
58+
for(let i=lowLen;i<=highLen;i++){
59+
for(let j=1;j<=10-i;j++){
60+
let str = ''
61+
let num = j
62+
str += num
63+
let k = i-1
64+
while(k--){
65+
num++
66+
str += num
67+
}
68+
let ans = parseInt(str)
69+
if(ans>=low && ans<=high){
70+
res.push(ans)
71+
}
72+
}
73+
}
74+
return res
75+
};
76+
```
77+
78+
79+
## 最后
80+
文章产出不易,还望各位小伙伴们支持一波!
81+
82+
往期精选:
83+
84+
<a href="https://github.com/Chocolate1999/Front-end-learning-to-organize-notes">小狮子前端の笔记仓库</a>
85+
86+
<a href="https://yangchaoyi.vip/">访问超逸の博客</a>,方便小伙伴阅读玩耍~
87+
88+
![](https://img-blog.csdnimg.cn/2020090211491121.png#pic_center)
89+
90+
```javascript
91+
学如逆水行舟,不进则退
92+
```
93+
94+

0 commit comments

Comments
 (0)