-
Notifications
You must be signed in to change notification settings - Fork 61
Expand file tree
/
Copy path1215-stepping-numbers.js
More file actions
53 lines (45 loc) · 1.3 KB
/
1215-stepping-numbers.js
File metadata and controls
53 lines (45 loc) · 1.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
/**
* 1215. Stepping Numbers
* https://leetcode.com/problems/stepping-numbers/
* Difficulty: Medium
*
* 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].
*/
/**
* @param {number} low
* @param {number} high
* @return {number[]}
*/
var countSteppingNumbers = function(low, high) {
const result = [];
if (low === 0) result.push(0);
const minLength = low.toString().length;
const maxLength = high.toString().length;
for (let length = minLength; length <= maxLength; length++) {
for (let start = 1; start <= 9; start++) {
dfs(start.toString(), length);
}
}
return result.sort((a, b) => a - b);
function dfs(current, targetLength) {
if (current.length === targetLength) {
const num = parseInt(current);
if (num >= low && num <= high) {
result.push(num);
}
return;
}
const lastDigit = parseInt(current[current.length - 1]);
if (lastDigit > 0) {
dfs(current + (lastDigit - 1), targetLength);
}
if (lastDigit < 9) {
dfs(current + (lastDigit + 1), targetLength);
}
}
};