[LeetCode] 247. 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.

Example:

Input:  n = 2
Output: ["11","69","88","96"]

 

這道題是之前那道 Strobogrammatic Number 的拓展,那道題讓我們判斷一個數是否是對稱數,而這道題讓找出長度為n的所有的對稱數,這里肯定不能一個數一個數的來判斷,那樣太不高效了,而且 OJ 肯定也不會答應。題目中給了提示說可以用遞歸來做,而且提示了遞歸調用 n-2,而不是 n-1。先來列舉一下n為 0,1,2,3,4 的情況:

n = 0:   none

n = 1:   0, 1, 8

n = 2:   11, 69, 88, 96

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

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;
    }
};

 

Github 同步地址:

https://github.com/grandyang/leetcode/issues/247

 

類似題目:

Strobogrammatic Number

Strobogrammatic Number III

 

參考資料:

https://leetcode.com/problems/strobogrammatic-number-ii/

https://leetcode.com/problems/strobogrammatic-number-ii/discuss/67280/AC-clean-Java-solution

https://leetcode.com/problems/strobogrammatic-number-ii/discuss/67288/Simple-Java-solution-without-recursion

 

LeetCode All in One 題目講解匯總(持續更新中...)


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM