[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 題目講解彙總(持續更新中...)

相關文章
相關標籤/搜索