[LeetCode] Stepping Numbers

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 while 421 is not.

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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
class Solution {
unordered_set<int> A;
void helper(long long now, long long l, long long r) {
if(now > r) return;
if(l <= now) A.insert(now);
int c = now % 10;
if(c != 9)
helper(now * 10 + c + 1, l, r);
if(c != 0)
helper(now * 10 + (c - 1 + 10) % 10, l, r);
}
public:
vector<int> countSteppingNumbers(int low, int high) {
for(int i = 0; i <= 9; i++)
helper(i, low, high);
vector<int> res(begin(A), end(A));
sort(begin(res),end(res));
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/08/25/PS/LeetCode/stepping-numbers/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.