A strobogrammatic number is a number that looks the same when rotated 180 degrees (looked at upside down).
Write a function to count the total strobogrammatic numbers that exist in the range of low <= num <= high.
Example:
Input: low = "50", high = "100" Output: 3 Explanation: 69, 88, and 96 are three strobogrammatic numbers.
Note:
Because the range might be a large number, the lowand high numbers are represented as string.
這道題是之前那兩道 Strobogrammatic Number II 和 Strobogrammatic Number 的拓展,又增加了難度,讓找給定范圍內的對稱數的個數,我們當然不能一個一個的判斷是不是對稱數,也不能直接每個長度調用第二道中的方法,保存所有的對稱數,然后再統計個數,這樣 OJ 會提示內存超過允許的范圍,所以這里的解法是基於第二道的基礎上,不保存所有的結果,而是在遞歸中直接計數,根據之前的分析,需要初始化 n=0 和 n=1 的情況,然后在其基礎上進行遞歸,遞歸的長度 len 從 low 到 high 之間遍歷,然后看當前單詞長度有沒有達到 len,如果達到了,首先要去掉開頭是0的多位數,然后去掉長度和 low 相同但小於 low 的數,和長度和 high 相同但大於 high 的數,然后結果自增1,然后分別給當前單詞左右加上那五對對稱數,繼續遞歸調用,參見代碼如下:
解法一:
class Solution { public: int strobogrammaticInRange(string low, string high) { int res = 0; for (int i = low.size(); i <= high.size(); ++i) { find(low, high, "", i, res); find(low, high, "0", i, res); find(low, high, "1", i, res); find(low, high, "8", i, res); } return res; } void find(string low, string high, string path, int len, int &res) { if (path.size() >= len) { if (path.size() != len || (len != 1 && path[0] == '0')) return; if ((len == low.size() && path.compare(low) < 0) || (len == high.size() && path.compare(high) > 0)) { return; } ++res; } find(low, high, "0" + path + "0", len, res); find(low, high, "1" + path + "1", len, res); find(low, high, "6" + path + "9", len, res); find(low, high, "8" + path + "8", len, res); find(low, high, "9" + path + "6", len, res); } };
上述代碼可以稍微優化一下,得到如下的代碼:
解法二:
class Solution { public: int strobogrammaticInRange(string low, string high) { int res = 0; find(low, high, "", res); find(low, high, "0", res); find(low, high, "1", res); find(low, high, "8", res); return res; } void find(string low, string high, string w, int &res) { if (w.size() >= low.size() && w.size() <= high.size()) { if (w.size() == high.size() && w.compare(high) > 0) { return; } if (!(w.size() > 1 && w[0] == '0') && !(w.size() == low.size() && w.compare(low) < 0)) { ++res; } } if (w.size() + 2 > high.size()) return; find(low, high, "0" + w + "0", res); find(low, high, "1" + w + "1", res); find(low, high, "6" + w + "9", res); find(low, high, "8" + w + "8", res); find(low, high, "9" + w + "6", res); } };
Github 同步地址:
https://github.com/grandyang/leetcode/issues/248
類似題目:
參考資料:
https://leetcode.com/problems/strobogrammatic-number-iii/
