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
Related Topics:
Array, String, Recursion
Similar Questions:
The strobogrammatic numbers are very sparse, so looping through all the n-digit numbers and test if they are strobogrammatic number is inefficient. We should try generating them.
We can use recursion/DFS/backtracking. In each recursion, we fill the i
th digit ([0,n/2]
), and fill the corresponding j = n-1-i
th digit.
// OJ: https://leetcode.com/problems/strobogrammatic-number-ii/
// Author: github.com/lzl124631x
// Time: O(5^(N/2))
// Space: O(N)
const char pairs[5][2] = {{'0','0'},{'1','1'},{'8','8'},{'6','9'},{'9','6'}};
class Solution {
public:
vector<string> findStrobogrammatic(int n) {
string s(n, '0');
vector<string> ans;
function<void(int)> dfs = [&](int i) {
if (i == (n + 1) / 2) {
ans.push_back(s);
return;
}
int j = n - 1 - i;
for (auto &[a, b] : pairs) {
if (i == j && a != b) continue;
if (i == 0 && n > 1 && a == '0') continue;
s[i] = a;
s[j] = b;
dfs(i + 1);
}
};
dfs(0);
return ans;
}
};