247. Strobogrammatic Number II
https://leetcode.com/problems/strobogrammatic-number-ii/description/
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"].
Thoughts
找到所有长度为n的对称数,每个数都以str形式。根据对称数的定义不断往两边拓展,有n为奇数或偶数两种情况。
Code
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;
}
};Analysis
时间复杂度O(N!). 一共有O(N!)个这样的strobogrammatic number.
Last updated
Was this helpful?