A strobogrammatic number is a number that looks the same when rotated 180 degrees (looked at upside down).
Find all strobogrammatic numbers that are of length = n.
For example,
Given n = 2, return ["11","69","88","96"].
class Solution {
public:
vector<string> findStrobogrammatic(int n) {
vector<string> res;
int start = 0;
if (n & 1 == 1) {
res.push_back("0");
res.push_back("1");
res.push_back("8");
start = 1;
} else res.push_back("");
for (int i = start; i < n; i += 2) {
vector<string> r;
for (auto s : res) {
if (i + 2 < n) r.push_back("0" + s + "0");
r.push_back("6" + s + "9");
r.push_back("9" + s + "6");
r.push_back("1" + s + "1");
r.push_back("8" + s + "8");
}
swap(res, r);
}
return res;
}
};
class Solution {
public List<String> findStrobogrammatic(int n) {
LinkedList<String> queue = new LinkedList<>();
if (n % 2 == 0) {
queue.add("");
} else {
queue.add("0");
queue.add("1");
queue.add("8");
}
boolean zero = true, proceed = true;
while (!queue.isEmpty()) {
int size = queue.size();
for (int i = 0; i < size; i++) {
String str = queue.remove(0);
if (str.length() == n - 2) {
zero = false;
} else if (str.length() == n) {
queue.add(str);
return queue;
}
if (zero) {
queue.add(0 + str + 0);
}
queue.add(6 + str + 9);
queue.add(9 + str + 6);
queue.add(8 + str + 8);
queue.add(1 + str + 1);
}
}
return queue;
}
}
时间复杂度O(N!). 一共有O(N!)个这样的strobogrammatic number.