[leetcode] 247. Strobogrammatic Number II 解题报告

题目链接: https://leetcode.com/problems/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:

  1. Try to use recursion and notice that it should recurse with n - 2 instead of n - 1.

思路: 我们可以分层的生成目标字符串, 也就是如果n是偶数, 那么字符可以两两配对即可, 如果n是奇数, 那么最内层只能是0, 1, 8, 那么递归到底之后再每次包围两个字符给他, 先产生最内层的字符串, 再产生外层的字符串. 在最外层不能是0.

代码如下:

class Solution {
public:
    vector<string> DFS(int n, int k)
    {
        if(n == 0) return {""};
        if(n == 1) return {"0", "1", "8"};
        vector<string> result;
        auto tem = DFS(n-2, k+1);
        int x = (k==0)?1:0;
        for(auto str: tem)
            for(int i = x; i< str1.size(); i++)
                result.push_back(str1[i]+str+str2[i]);
        return result;
    }
    
    vector<string> findStrobogrammatic(int n) {
        return DFS(n, 0);
    }
private:
    string str1 = "01689";
    string str2 = "01986";
};

参考: https://leetcode.com/discuss/91785/concise-and-simple-c-solution-with-explaination

你可能感兴趣的:(LeetCode,String)