[LeetCode247]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.

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

Hint:

Try to use recursion and notice that it should recurse with n - 2 instead of n - 1.
Hide Company Tags Google
Hide Tags Math Recursion
Hide Similar Problems (E) Strobogrammatic Number (H) Strobogrammatic Number III

根据题目描述:
n = 1: 0, 1, 8
n = 2: 11, 69, 96, 88

一如既往没什么思路, 提示也看不懂, 就看大家的智慧结晶,然后秒懂,这奇怪的s数,一定要保持upsidedown之后跟以前的一模一样, 所以如果n = 4, 我们就需要把 n = 2 每一种可能两头加上我们的candidate, 这样的处理能保证得到的四位数也是s数。比如对于”11”, 两头分别加: 11, 69, 96, 88是没有问题的,但是不能加00。因为0110并不make sense。

如何处理0?根据提示和上述分析, 利用recursion解题我们recur n-2, 所以当n=4时,在 m = 2那个环节,产生“00“这样的组合是make sense的!所以有了下面的code。

class Solution {
public:
    vector<string> helper(int n, int m){
        if( !n ) return {""};
        if(n == 1) return {"0","1","8"};
        vector<string> res;
        vector<string> tmp;
        tmp = helper(n-2, m);
        for(int i = 0; i<tmp.size(); ++i){
            string s = tmp[i];
            if( n != m) res.push_back("0" + s + "0");
            res.push_back("1" + s + "1");
            res.push_back("6" + s + "9");
            res.push_back("8" + s + "8");
            res.push_back("9" + s + "6");
        }
        return res;
    }

    vector<string> findStrobogrammatic(int n) {
       return helper(n,n);
    }
};

你可能感兴趣的:(LeetCode)