Leetcode 247 中心对称数 II 找规律递推

Leetcode 247 中心对称数 II 找规律递推_第1张图片

 

当 n=0 的时候,应该输出空字符串:“ ”。

当 n=1 的时候,也就是长度为 1 的中心对称数有:0,1,8。

当 n=2 的时候,长度为 2 的中心对称数有:11, 69,88,96。注意:00 并不是一个合法的结果。

当 n=3 的时候,只需要在长度为 1 的合法中心对称数的基础上,不断地在两边添加 11,69,88,96 就可以了。

[101, 609, 808, 906,     111, 619, 818, 916,     181, 689, 888, 986]

随着 n 不断地增长,我们只需要在长度为 n-2 的中心对称数两边添加 11,69,88,96 即可。

 

但是要注意,中间过程可以在两步添加00,比如四位8008,所以用滚动数组或者递归均可以完成。

class Solution {
public:
    vector findStrobogrammatic(int n) {
        vector one = {""};
        vector two{"0","1","8"};
        vector res;
        if(n<=0) return one;
        if(n==1) return two;
        for(int i=2;i<=n;i++){
            for(auto ans:one){
                string tmp;
                if(i!=n) {
                    tmp = "0"+ans+"0";
                    res.push_back(tmp);

                }
                tmp = "1"+ans+"1";
                res.push_back(tmp);
                tmp = "6"+ans+"9";
                res.push_back(tmp);
                tmp = "8"+ans+"8";
                res.push_back(tmp);
                tmp = "9"+ans+"6";
                res.push_back(tmp);
            }
            one = two;
            two = res;
            res.clear();
        }
        return two;
    }
};

 

你可能感兴趣的:(算法)