Tuesday, December 29, 2015

247. Strobogrammatic Number II --------M

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"]
A:
递归
一开始是允许0开始的,最后再删掉。
class Solution {
public:
    vector<string> findStrobogrammatic(int n) {
        vector<string> res;
        if(n<=0){
            return res;
        }
        for(auto s: helper(n)){
            if(s.length()== 1 || s[0] !='0'){// remove number starting with 0
                res.push_back(s);
            }
        }
        return res;
    }
private:
    vector<string> helper(int n ){        
        if(n==1){
            return vector<string>{"0","1","8"};
        }
        if(n==2){
            return vector<string>{"11","69","88","96","00"};
        }else{
            vector<string> res;
            for(auto ss : helper(n-2)){
                res.push_back("0"+ss+"0");
                res.push_back("1"+ss+"1");
                res.push_back("8"+ss+"8");
                res.push_back("6"+ss+"9");
                res.push_back("9"+ss+"6");
            }
            return res;
        }
    }
};


但会造成多用了时间, 因此,多加了个N参数,来标记是否是最外层。
可是结果反而慢了,好奇怪



Mistakes:

1: 记得不能以0 开头,但是忘记了, n ==1 的时候, "0"也是可以的。




No comments:

Post a Comment