[Swift]LeetCode1215. 步进数 | Stepping Numbers

★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★

➤微信公众号:山青咏芝(let_us_code)

➤博主域名:https://www.zengqiang.org

➤GitHub地址:https://github.com/strengthen/LeetCode

➤原文地址:

➤如果链接不是山青咏芝的博客园地址,则可能是爬取作者的文章。

➤原文已修改更新!强烈建议点击原文地址阅读!支持作者!支持原创!

★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★

热烈欢迎,请直接点击!!!

进入博主App Store主页,下载使用各个作品!!!

注:博主将坚持每月上线一个新app!!!

A Stepping Number is an integer such that all of its adjacent digits have an absolute difference of exactly 1. For example, 321 is a Stepping Number while 421 is not.

Given two integers low and high, find and return a sorted list of all the Stepping Numbers in the range [low, high] inclusive.

Example 1:

Input: low = 0, high = 21
Output: [0,1,2,3,4,5,6,7,8,9,10,12,21]

Constraints:

  • 0 <= low <= high <= 2 * 10^9

如果一个整数上的每一位数字与其相邻位上的数字的绝对差都是 1,那么这个数就是一个「步进数」。

例如,321 是一个步进数,而 421 不是。

给你两个整数,lowhigh,请你找出在 [low, high] 范围内的所有步进数,并返回 排序后 的结果。

示例:

输入:low = 0, high = 21
输出:[0,1,2,3,4,5,6,7,8,9,10,12,21]

提示:

  • 0 <= low <= high <= 2 * 10^9

Runtime: 152 ms

Memory Usage: 22.3 MB

 1 class Solution {
 2     var L:Int = 0
 3     var S:[Int] = [Int]()
 4     
 5     func countSteppingNumbers(_ low: Int, _ high: Int) -> [Int] {
 6         self.L = high
 7         var ans:[Int] = [Int]()
 8         for i in 1...9
 9         {
10             search(i)
11         }
12         if 0 >= low && 0 <= high
13         {
14             ans.append(0)
15         }
16         for i in S
17         {
18             if i >= low && i <= high
19             {
20                 ans.append(i)
21             }
22         }
23         ans.sort()
24         return ans
25     }
26     
27     func search(_ x:Int)
28     {
29         if x > L{return}
30         S.append(x)
31         let last:Int = x % 10
32         if last != 0
33         {
34             search(x * 10 + last - 1)
35         }
36         if last != 9
37         {
38             search(x * 10 + last + 1)
39         }
40     }  
41 }