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.

Tips:

我觉得还是挺简单的,就是把n-2的结果的外层 + 可能的几个数。

Code:

public class Solution {
    public List<String> findStrobogrammatic(int n) {
        List<String> answer = new ArrayList<String>();
        helper(answer, n, n);
        return answer;
    }

    public void helper(List<String> list, int n, int targetLen){
        if(n == 0){
            list.add("");
            return; 
        }
        if(n == 1){
            list.add("0");
            list.add("1");
            list.add("8");
            return;
        }
        helper(list, n - 2, targetLen);
        int size = list.size();
        int i = 0;
        while(i < size){
            String cur = list.get(i);
            if(n != targetLen){
                list.add("0" + cur + "0");
            }
            list.add("1" + cur + "1");
            list.add("6" + cur + "9");
            list.add("8" + cur + "8");
            list.add("9" + cur + "6");
            list.remove(0);
            size--;
        }
    }
}

results matching ""

    No results matching ""