LeetCode 247. Strobogrammatic Number II

来源:互联网 发布:msn即时软件 编辑:程序博客网 时间:2024/05/22 20:29

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.

思路:
1. 找规律。
- n=0, 无,容易忽略n=0
- n=1, {0,1,8}
- n=2, {11,69,88,96}
- n=3, {101,111,181,609,619,689,808,818,888,906,916,986}
2. n=3是n=1的所有可能在两边分别加1x1,6x9,9x6,8x8即可;n=2是 n=0的情况在左右加1x1,6x9,9x6,8x8即可。所以奇偶分别对待。

vector<string> findStrobogrammatic(int n) {    //iterative    vector<string> one={"0","1","8"},zero="";    vector<string> res=zero;    if(n%2)//奇数        res=one;    for(int i=n%2;i<=n-2;i+=2){        vector<string> cur;        for(auto&s:res){            if(i<n-2) cur.push_back('0'+s+'0');//由于一层一层的加数字,最外一层不能首尾加0,内层可以首尾加0.            cur.push_back('1'+s+'1');            cur.push_back('6'+s+'9');            cur.push_back('8'+s+'8');            cur.push_back('9'+s+'6');        }        res=cur;    }    return res;}
0 0
原创粉丝点击