标签:new solution 描述 分析 输出 数字 tst 情况 ++
如果一个整数上的每一位数字与其相邻位上的数字的绝对差都是 1
,那么这个数就是一个「步进数」。
例如,321
是一个步进数,而 421
不是。
给你两个整数,low
和 high
,请你找出在 [low, high]
范围内的所有步进数,并返回 排序后 的结果。
示例 :
输入:low = 0, high = 21
输出:[0,1,2,3,4,5,6,7,8,9,10,12,21]
提示:
0 <= low <= high <= 2 * 10^9
>=low && <= high
的数添加到结果集合 result,最后排下序。代码:
class Solution {
public List<Integer> countSteppingNumbers(int low, int high) {
List<Integer> list = new ArrayList<>();
list.add(0);
for (int i = 1; i <= 9; i++) {
dfs(list, i);
}
List<Integer> result = new ArrayList<>();
for (int num : list) {
if (num >= low && num <= high) {
result.add(num);
}
}
Collections.sort(result);
return result;
}
public void dfs(List<Integer> list, int cur) {
list.add(cur);
if (cur > Integer.MAX_VALUE / 10) {
return;
}
int r = cur % 10;
if (r != 9) {
dfs(list, cur * 10 + r + 1);
}
if (r != 0) {
dfs(list, cur * 10 + r - 1);
}
}
}
代码:
class Solution {
public List<Integer> countSteppingNumbers(int low, int high) {
List<Integer> result = new ArrayList<>();
if (low == 0) {
result.add(0);
}
for (int i = 1; i <= 9; i++) {
dfs(result, i, low, high);
}
Collections.sort(result);
return result;
}
public void dfs(List<Integer> result, int cur, int low, int high) {
if (cur >= low && cur <= high) {
result.add(cur);
}
if (cur > high / 10) {
return;
}
int r = cur % 10;
if (r != 9 && cur * 10 + r + 1 <= high) {
dfs(result, cur * 10 + r + 1, low, high);
}
if (r != 0 && cur * 10 + r - 1 <= high) {
dfs(result, cur * 10 + r - 1, low, high);
}
}
}
代码:
class Solution {
public List<Integer> countSteppingNumbers(int low, int high) {
Queue<Integer> queue = new LinkedList<>();
List<Integer> result = new ArrayList<>();
if (low == 0) {
result.add(0);
}
for (int i = 1; i <= 9; i++) {
queue.offer(i);
}
while (!queue.isEmpty()) {
int cur = queue.poll();
if (cur >= low && cur <= high) {
result.add(cur);
}
if (cur > high / 10) {
continue;
}
int r = cur % 10;
if (r != 9 && cur * 10 + r + 1 <= high) {
queue.offer(cur * 10 + r + 1);
}
if (r != 0 && cur * 10 + r - 1 <= high) {
queue.offer(cur * 10 + r - 1);
}
}
Collections.sort(result);
return result;
}
}
就是以 1 到 9 开头,求出步进数,可以用 DFS,也可以用 BFS。
标签:new solution 描述 分析 输出 数字 tst 情况 ++
原文地址:https://www.cnblogs.com/qiu_jiaqi/p/LeetCode_5081.html