-
Notifications
You must be signed in to change notification settings - Fork 12
/
247. Strobogrammatic Number II.cpp
72 lines (56 loc) · 1.63 KB
/
247. Strobogrammatic Number II.cpp
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
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
/*
Problem link: https://leetcode.com/problems/strobogrammatic-number-ii/
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
*/
// Milon
class Solution {
public:
string rotatedStr(string str) {
for (auto &ch : str) {
ch = rotatedDigit[ch];
}
reverse(str.begin(), str.end());
return str;
}
void solve(int rem, const string &cur, vector<string> &ans) {
if (rem == 0) {
string tmp = rotatedStr(cur);
ans.push_back(cur + tmp);
return;
} else if (rem == 1) {
string tmp = rotatedStr(cur);
ans.push_back(cur + '0' + tmp);
ans.push_back(cur + '1' + tmp);
ans.push_back(cur + '8' + tmp);
return;
}
for (auto d : digits) {
if (d == '0' && cur == "")
continue;
solve(rem - 2, cur + d, ans);
}
}
vector<string> findStrobogrammatic(int n) {
rotatedDigit['0'] = '0';
rotatedDigit['1'] = '1';
rotatedDigit['6'] = '9';
rotatedDigit['8'] = '8';
rotatedDigit['9'] = '6';
vector<string> ans;
string cur = "";
solve(n, cur, ans);
return ans;
}
private:
unordered_map<char, char> rotatedDigit;
vector<char> digits {'0', '1', '6', '8', '9'};
};