Leetcode 0247: 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.

Example:

Input: n = 2
Output: [“11”,“69”,“88”,“96”]

Time complexity: O(n)
观察规律:
n == 1: 0, 1, 8
n == 2: 11, 88, 69, 96
n ==3:
101 111 181
808 818 888
609 619 689
906 916 986
n ==4:
1111 1881 1691 1961 1001
8118 8888 8698 8968 8008
6119 6889 6699 6969 6009
9116 9886 9696 9966 9006
对于 n>= 3 来说:如果 字符串s 是一个 strobogrammatic 则
1s1, 8s8, 6s9, 9s6, 0s0 都是strobogrammatic。 所以我们可以递归每次从最前端和最后端缩短两个字符。注意0不能作为开头。

class Solution {
    
    
    private static final char[][] PAIRS = new char[][] {
    
    
        {
    
    '0', '0'}, {
    
    '1', '1'}, {
    
    '6', '9'}, {
    
    '8', '8'}, {
    
    '9', '6'}};
    List<String> res = new ArrayList<>();
    public List<String> findStrobogrammatic(int n) {
    
    
        if (n == 0) return Arrays.asList("");
        if (n == 1) return Arrays.asList("0", "1", "8");
        dfs(new char[n], 0, n-1);
        return res;
    }
    
    void dfs(char[] buffer, int left, int right){
    
    
        if (left > right) {
    
    
            res.add(String.valueOf(buffer));
            return;
        }
        for(char[] p : PAIRS){
    
    
            if (buffer.length != 1 && left == 0 && p[0] == '0') {
    
    
                continue; 
            }
            if (left == right && (p[0] == '6' || p[0] == '9')) {
    
    
                continue; 
            }
            buffer[left] = p[0];
            buffer[right] = p[1];
            dfs(buffer, left+1, right-1);
        }
    }
}
class Solution {
    
    
    
    public List<String> findStrobogrammatic(int n) {
    
    
        return helper(n, n);
    }
    
    List<String> helper(int n, int len){
    
    
        if (n == 0) return Arrays.asList("");
        if (n == 1) return Arrays.asList("0", "1", "8");
        List<String> list = helper(n - 2, len);
        List<String> res = new ArrayList<String>();
        for(String s:list){
    
    
            if (n != len) {
    
    
                res.add("0" + s + "0");
            }
            res.add("1" + s + "1");
            res.add("6" + s + "9");
            res.add("8" + s + "8");
            res.add("9" + s + "6");
        }
        return res;
        
    }
}

猜你喜欢

转载自blog.csdn.net/weixin_43946031/article/details/113917866