247. Strobogrammatic Number II π
Description
Given an integer n, return all the strobogrammatic numbers that are of length n. You may return the answer in any order.
A strobogrammatic number is a number that looks the same when rotated 180 degrees (looked at upside down).
Example 1:
Input: n = 2 Output: ["11","69","88","96"]
Example 2:
Input: n = 1 Output: ["0","1","8"]
Constraints:
1 <= n <= 14
Solutions
Solution 1: Recursion
Thinking
Length-\(n\) strobogrammatic numbers are shorter valid strings with a mirrored pair wrapped around them. Length \(1\) is \(0,1,8\); length \(0\) is the empty string.
\(dfs(u)\) wraps \(11,88,69,96\) around \(dfs(u-2)\), and wraps \(00\) only when \(u\neq n\) so the full number has no leading zero.
If the length is \(1\), then the strobogrammatic numbers are only \(0, 1, 8\); if the length is \(2\), then the strobogrammatic numbers are only \(11, 69, 88, 96\).
We design a recursive function \(dfs(u)\), which returns the strobogrammatic numbers of length \(u\). The answer is \(dfs(n)\).
If \(u\) is \(0\), return a list containing an empty string, i.e., [""]; if \(u\) is \(1\), return the list ["0", "1", "8"].
If \(u\) is greater than \(1\), we traverse all the strobogrammatic numbers of length \(u - 2\). For each strobogrammatic number \(v\), we add \(1, 8, 6, 9\) to both sides of it, and we can get the strobogrammatic numbers of length u.
Note that if \(u \neq n\), we can also add \(0\) to both sides of the strobogrammatic number.
Finally, we return all the strobogrammatic numbers of length \(n\).
The time complexity is \(O(2^{n+2})\).
Similar problems:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | |
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 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | |