|
34 | 34 |
|
35 | 35 | **方法一:BFS**
|
36 | 36 |
|
| 37 | +首先,如果 $low$ 为 0ドル,ドル那么我们需要将 0ドル$ 加入答案中。 |
| 38 | + |
| 39 | +接下来,我们创建一个队列 $q,ドル并将 1ドル \sim 9$ 加入队列中。然后我们不断从队列中取出元素,记当前元素为 $v,ドル如果 $v$ 大于 $high,ドル那么我们就停止搜索;如果 $v$ 在 $[low, high]$ 的范围内,那么我们将 $v$ 加入答案中。然后,我们需要将 $v$ 的最后一位数字记为 $x,ドル如果 $x \gt 0,ドル那么我们将 $v \times 10 + x - 1$ 加入队列中;如果 $x \lt 9,ドル那么我们将 $v \times 10 + x + 1$ 加入队列中。重复上述操作,直到队列为空。 |
| 40 | + |
| 41 | +时间复杂度 $O(10 \times 2^{\log M}),ドル空间复杂度 $O(2^{\log M}),ドル其中 $M$ 为 $high$ 的位数。 |
| 42 | + |
37 | 43 | <!-- tabs:start -->
|
38 | 44 |
|
39 | 45 | ### **Python3**
|
@@ -104,17 +110,29 @@ class Solution {
|
104 | 110 | public:
|
105 | 111 | vector<int> countSteppingNumbers(int low, int high) {
|
106 | 112 | vector<int> ans;
|
107 | | - if (low == 0) ans.push_back(0); |
| 113 | + if (low == 0) { |
| 114 | + ans.push_back(0); |
| 115 | + } |
108 | 116 | queue<long long> q;
|
109 | | - for (int i = 1; i < 10; ++i) q.push(i); |
| 117 | + for (int i = 1; i < 10; ++i) { |
| 118 | + q.push(i); |
| 119 | + } |
110 | 120 | while (!q.empty()) {
|
111 | | - int v = q.front(); |
| 121 | + long long v = q.front(); |
112 | 122 | q.pop();
|
113 | | - if (v > high) break; |
114 | | - if (v >= low) ans.push_back(v); |
| 123 | + if (v > high) { |
| 124 | + break; |
| 125 | + } |
| 126 | + if (v >= low) { |
| 127 | + ans.push_back(v); |
| 128 | + } |
115 | 129 | int x = v % 10;
|
116 | | - if (x) q.push(1ll * v * 10 + x - 1); |
117 | | - if (x < 9) q.push(1ll * v * 10 + x + 1); |
| 130 | + if (x > 0) { |
| 131 | + q.push(v * 10 + x - 1); |
| 132 | + } |
| 133 | + if (x < 9) { |
| 134 | + q.push(v * 10 + x + 1); |
| 135 | + } |
118 | 136 | }
|
119 | 137 | return ans;
|
120 | 138 | }
|
@@ -151,6 +169,38 @@ func countSteppingNumbers(low int, high int) []int {
|
151 | 169 | }
|
152 | 170 | ```
|
153 | 171 |
|
| 172 | +### **TypeScript** |
| 173 | + |
| 174 | +```ts |
| 175 | +function countSteppingNumbers(low: number, high: number): number[] { |
| 176 | + const ans: number[] = []; |
| 177 | + if (low === 0) { |
| 178 | + ans.push(0); |
| 179 | + } |
| 180 | + const q: number[] = []; |
| 181 | + for (let i = 1; i < 10; ++i) { |
| 182 | + q.push(i); |
| 183 | + } |
| 184 | + while (q.length) { |
| 185 | + const v = q.shift()!; |
| 186 | + if (v > high) { |
| 187 | + break; |
| 188 | + } |
| 189 | + if (v >= low) { |
| 190 | + ans.push(v); |
| 191 | + } |
| 192 | + const x = v % 10; |
| 193 | + if (x > 0) { |
| 194 | + q.push(v * 10 + x - 1); |
| 195 | + } |
| 196 | + if (x < 9) { |
| 197 | + q.push(v * 10 + x + 1); |
| 198 | + } |
| 199 | + } |
| 200 | + return ans; |
| 201 | +} |
| 202 | +``` |
| 203 | + |
154 | 204 | ### **...**
|
155 | 205 |
|
156 | 206 | ```
|
|
0 commit comments