We can generate stepping numbers by starting from each digit (0-9) and appending digits that differ by 1 from the last digit. BFS ensures we generate numbers in increasing order and avoid duplicates. This approach is efficient for the given range.
classSolution {
funcountSteppingNumbers(low: Int, high: Int): List<Int> {
val ans = mutableListOf<Int>()
if (low ==0) ans.add(0)
for (i in1..9) {
val q = ArrayDeque<Long>()
q.add(i.toLong())
while (q.isNotEmpty()) {
val num = q.removeFirst()
if (num > high) continueif (num >= low) ans.add(num.toInt())
val last = num % 10if (last > 0) q.add(num * 10 + (last - 1))
if (last < 9) q.add(num * 10 + (last + 1))
}
}
ans.sort()
return ans
}
}
classSolution:
defcountSteppingNumbers(self, low: int, high: int) -> list[int]:
ans: list[int] = []
if low ==0:
ans.append(0)
for i in range(1, 10):
q = [i]
while q:
num = q.pop(0)
if num > high:
continueif num >= low:
ans.append(num)
last = num %10if last >0:
next_num = num *10+ (last -1)
if next_num <= high:
q.append(next_num)
if last <9:
next_num = num *10+ (last +1)
if next_num <= high:
q.append(next_num)
ans.sort()
return ans
impl Solution {
pubfncount_stepping_numbers(low: i32, high: i32) -> Vec<i32> {
letmut ans = Vec::new();
if low ==0 {
ans.push(0);
}
for i in1..=9 {
letmut q = std::collections::VecDeque::new();
q.push_back(i asi64);
whilelet Some(num) = q.pop_front() {
if num > high asi64 { continue; }
if num >= low asi64 { ans.push(num asi32); }
let last = num %10;
if last >0 {
let next = num *10+ (last -1);
if next <= high asi64 {
q.push_back(next);
}
}
if last <9 {
let next = num *10+ (last +1);
if next <= high asi64 {
q.push_back(next);
}
}
}
}
ans.sort();
ans
}
}