题目链接: https://leetcode.com/problems/strobogrammatic-number-ii/
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"]
.
Hint:
- Try to use recursion and notice that it should recurse with n - 2 instead of n - 1.
思路: 可以像是一层层的给字符串从里向外穿衣服一样DFS生成所有的解.
其中翻转之后和自身相等有0, 1, 8, 在n为奇数的情况下最里面的一个数可以为这三个数的任意一个. 再外边就一次给两端添加一个对称的字符. 如果是最外层的话需要注意不能是为0.
代码如下:
class Solution {
public:
void DFS(int n, string str)
{
if(n==0) return result.push_back(str);
if(n%2==1) for(auto val: same) DFS(n-1, val);
if(n%2==1) return;
for(int i = (n==2)?1:0; i < two.size(); i++)
DFS(n-2, two[i].first + str + two[i].second);
}
vector<string> findStrobogrammatic(int n) {
if(n <= 0) return {};
DFS(n, "");
return result;
}
private:
vector<string> result;
vector<string> same{"0", "1", "8"};
vector<pair<char,char>> two{{'0','0'},{'1','1'},{'6','9'},{'8','8'},{'9','6'}};
};