LeetCode 1215. Stepping Numbers

原题链接在这里:https://leetcode.com/problems/stepping-numbers/

题目:

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, find and return a sorted list of all the Stepping Numbers in the range [low, high] inclusive.

Example 1:

Input: low = 0, high = 21
Output: [0,1,2,3,4,5,6,7,8,9,10,12,21]

Constraints:

  • 0 <= low <= high <= 2 * 10^9

题解:

The candidate stepping numbers starting from 1, 2, 3...9.

If the current stepping number is 1, the generated ones based on it could 10 or 12.

Use BFS to iteate all possible candidates, if current number is within [low, high], add it to res.

Ortherwise, if it is <= high/10, in case of overflow, add its generated numbers to queue.

Corner case is 0. If low is 0, add it specifically. Because generated number 01 is not leagal.

Time Complexity: O(2^n). 9*(2^0 + 2^1 + 2^2 + ... + 2^n). n is digit number of high.

Space: O(2^n).

AC Java:

 1 class Solution {
 2     public List<Integer> countSteppingNumbers(int low, int high) {
 3         List<Integer> res = new ArrayList<>();
 4         if(low > high){
 5             return res;
 6         }
 7         
 8         LinkedList<Integer> que = new LinkedList<>();
 9         for(int i = 1; i<=9; i++){
10             que.add(i);
11         }
12         
13         if(low == 0){
14             res.add(0);
15         }
16         
17         while(!que.isEmpty()){
18             int cur = que.poll();
19             if(cur >= low && cur <= high){
20                 res.add(cur);
21             }
22             
23             if(cur <= high/10){
24                 int lastDigit = cur%10;
25                 if(lastDigit > 0){
26                     que.add(cur*10 + lastDigit - 1);
27                 }
28                 
29                 if(lastDigit < 9){
30                     que.add(cur*10 + lastDigit + 1);
31                 }
32             }
33         }
34         
35         return res;
36     }
37 }

 

posted @ 2019-11-11 10:22  Dylan_Java_NYC  阅读(814)  评论(0编辑  收藏  举报