[LeetCode] Strobogrammatic Number II 对称数之二

 

A strobogrammatic number is a number that looks the same when rotated 180 degrees (looked at upside down).html

Find all strobogrammatic numbers that are of length = n.java

For example,
Given n = 2, return ["11","69","88","96"].ide

Hint:post

  1. Try to use recursion and notice that it should recurse with n - 2 instead of n - 1.

 

这道题是以前那道Strobogrammatic Number的拓展,那道题让咱们判断一个数是不是对称数,而这道题让咱们找出长度为n的全部的对称数,咱们确定不能一个数一个数的来判断,那样太不高效了,并且OJ确定也不会答应。题目中给了提示说能够用递归来作,并且提示了递归调用n-2,而不是n-1。咱们先来列举一下n为0,1,2,3,4的状况:url

n = 0:   nonespa

n = 1:   0, 1, 8code

n = 2:   11, 69, 88, 96htm

n = 3:   101, 609, 808, 906, 111, 619, 818, 916, 181, 689, 888, 986blog

n = 4:   1001, 6009, 8008, 9006, 1111, 6119, 8118, 9116, 1691, 6699, 8698, 9696, 1881, 6889, 8888, 9886, 1961, 6969, 8968, 9966递归

咱们注意观察n=0和n=2,能够发现后者是在前者的基础上,每一个数字的左右增长了[1 1], [6 9], [8 8], [9 6],看n=1和n=3更加明显,在0的左右增长[1 1],变成了101, 在0的左右增长[6 9],变成了609, 在0的左右增长[8 8],变成了808, 在0的左右增长[9 6],变成了906, 而后在分别在1和8的左右两边加那四组数,咱们其实是从m=0层开始,一层一层往上加的,须要注意的是当加到了n层的时候,左右两边不能加[0 0],由于0不能出如今两位数及多位数的开头,在中间递归的过程当中,须要有在数字左右两边各加上0的那种状况,参见代码以下:  

 

解法一:

class Solution {
public:
    vector<string> findStrobogrammatic(int n) {
        return find(n, n);
    }
    vector<string> find(int m, int n) {
        if (m == 0) return {""};
        if (m == 1) return {"0", "1", "8"};
        vector<string> t = find(m - 2, n), res;
        for (auto a : t) {
            if (m != n) res.push_back("0" + a + "0");
            res.push_back("1" + a + "1");
            res.push_back("6" + a + "9");
            res.push_back("8" + a + "8");
            res.push_back("9" + a + "6");
        }
        return res;
    }
};

 

这道题还有迭代的解法,感受也至关的巧妙,须要从奇偶来考虑,奇数赋为0,1,8,偶数赋为空,若是是奇数,就从i=3开始搭建,由于计算i=3须要i=1,而咱们已经初始化了i=1的状况,若是是偶数,咱们从i=2开始搭建,咱们也已经初始化了i=0的状况,因此咱们能够用for循环来搭建到i=n的状况,思路和递归同样,写法不一样而已,参见代码以下:

 

解法二:

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

 

相似题目:

Strobogrammatic Number

Strobogrammatic Number III

 

参考资料:

https://leetcode.com/discuss/68215/simple-java-solution-without-recursion

https://leetcode.com/discuss/85991/14-lines-concise-and-easy-understand-c-solution

 

LeetCode All in One 题目讲解汇总(持续更新中...)

相关文章
相关标签/搜索