247. Strobogrammatic Number II

Description

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"]

Solution

DFS, O(k ^ n), S(n)

其实就是组合问题呀,每两位成对儿出现计算组合数,另外如果n为奇数最中间的位置只能选择旋转过后不变的数字。另外还需要排除开头结尾是0的组合(但n = 1时允许)。

可以发现这是一个尾递归,可以轻松改成迭代模式。

class Solution {
    private static final int[] SINGLES = {0, 1, 8};
    private static final int[][] PAIRS = {{0, 0}, {1, 1}, {6, 9}, {8, 8}, {9, 6}};
    
    public List findStrobogrammatic(int n) {
        List list = new ArrayList<>();
        char[] arr = new char[n];
        dfs(arr, 0, arr.length - 1, list);
        return list;
    }
    
    private void dfs(char[] arr, int left, int right, List list) {
        if (left > right) {
            list.add(new String(arr));
            return;
        }
        
        if (left == right) {
            for (int v : SINGLES) {
                if (v == 0 && left == 0 && arr.length > 1) {// 0 is valid, 010 is not
                    continue;
                }
                arr[left] = (char) (v + '0');
                dfs(arr, left + 1, right - 1, list);
            }
        } else {
            for (int[] pair : PAIRS) {
                if (pair[0] == 0 && left == 0) {
                    continue;
                }            
                
                arr[left] = (char) (pair[0] + '0');
                arr[right] = (char) (pair[1] + '0');
                dfs(arr, left + 1, right - 1, list);
            }
        }
    }
}

Iterative

从中间往两端扩展。

class Solution {
    public List findStrobogrammatic(int n) {
        List list = n % 2 == 0 ? 
            Arrays.asList("") : Arrays.asList("0", "1", "8");
        for (int i = n % 2 == 0 ? 0 : 1; i < n; i += 2) {
            List newList = new ArrayList<>();
            
            for (String s : list) {
                if (i + 2 < n) {
                    newList.add("0" + s + "0");
                }
                newList.add("1" + s + "1");
                newList.add("6" + s + "9");
                newList.add("8" + s + "8");
                newList.add("9" + s + "6");
            }
            
            list = newList;
        }
        
        return list;
    }
}

你可能感兴趣的:(247. Strobogrammatic Number II)