[LeetCode248]Strobogrammatic Number III

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.

For example,
Given low = "50", high = "100", return 3. Because 69, 88, and 96 are three strobogrammatic numbers.

Note:
Because the range might be a large number, the low and high numbers are represented as string.

Hide Tags Math Recursion
Hide Similar Problems (E) Strobogrammatic Number (M) Strobogrammatic Number II

这题比前两道更难一点,但有一点相似的是:还是从两头开始向中间处理。
Basic idea: generate all possible strobogrammatic numbers in between low and high by using backtracking, and count the total count.

class Solution {
public:
    int strobogrammaticInRange(string low, string high) {
        int cnt = 0, lowSize = low.size(), highSize = high.size();
        for(int i = lowSize; i <= highSize; ++i){
            string tmp(i,' ');
            helper(tmp, cnt, low, high, 0, i-1);
        }
        return cnt;
    }
private:
    unordered_map<char, char> mp ={{'0', '0'}, {'1', '1'}, {'6', '9'}, {'8', '8'}, {'9', '6'}};
    void helper(string tmp, int& cnt, string& low, string& high, int start, int end){
        if(start > end){
            if( (tmp[0] != '0' || tmp.size() == 1) &&isLess(low,tmp) && isLess(tmp,high)) ++cnt;
            return;
        }

        for(auto m : mp){
            tmp[start] = m.first;
            tmp[end] = m.second;
            if((start < end) || (start == end) && m.first == m.second)
                helper(tmp, cnt, low, high, start+1, end-1);
        }
    }
    bool isLess(string s, string t){
        if(s.size() != t.size() ) return s.size() < t.size();
        for(int i = 0; i< s.size(); ++i){
            if(s[i] < t[i]) return true;
            else if(s[i] > t[i]) return false;
        }
        return true;
    }
};

满足的条件是:tmp在low 和 high 之间并且它不是以0开头的(除非它的size是1) +cnt.

PS:还有0ms的解法,但我没看懂。。不,是我偷懒了,不想看。。。
https://leetcode.com/discuss/65270/solution-without-actually-generating-strobogrammatic-numbers

你可能感兴趣的:(LeetCode)