题目描述:
自己的提交:参考全排列
class Solution: def countSteppingNumbers(self, low: int, high: int) -> List[int]: a = [i for i in range(10)] res =[] def helper(num): if low<=num<=high and num not in res: res.append(num) if num>=high: return if num%10+1<=9:helper(num*10+(num%10+1)) if num%10-1>=0:helper(num*10+(num%10-1)) for i in a: helper(i) res.sort() return res
优化:
class Solution(object): def countSteppingNumbers(self, low, high): ans = set() def search(x): if x > high: return if x >= low: ans.add(x) last = x % 10 for d in (last-1, last+1): if 0 <= d < 10: search(10 * x + d) for d in range(10): search(d) return sorted(ans)