【leetcode】1215.Stepping Numbers
题目如下:
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 while421
is not.Given two integers
low
andhigh
, 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
解题思路:如果x是一个Stepping Number,假设x的个位是y,那么x*10 + y - 1 (y-1 >=0) 和 x*10 + y + 1 (y+1<=9) 也是Stepping Number,根据这个规律把所有符合条件的数字求出来即可。
代码如下:
class Solution(object): def countSteppingNumbers(self, low, high): """ :type low: int :type high: int :rtype: List[int] """ queue = range(0,10) res = set() while len(queue) > 0: val = queue.pop(0) if val >= low and val <= high: res.add(val) last = int(str(val)[-1]) if last < 9: new_val = int(str(val) + str(last+1)) if new_val <= high: queue.append(new_val) if last > 0: new_val = int(str(val) + str(last-1)) if new_val <= high: queue.append(new_val) return sorted(list(res))