[LeetCode] 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"].

 

Run some examples

n = 0, null;
n = 1, [0, 1, 8]
n = 2, [11, 69, 88, 96]
n = 3, [101, 609, 808, 906,
111, 619, 818, 916,
181, 689, 888, 986]
n = 4, [1001, 6009, 8008, 9006,
1111, 6119, 8118, 9116,
1691, 6699, 8698, 9696,
1881, 6889, 8888, 9886,
1961, 6969, 8968, 9966]

Brainstorming:
For a given n, each of its result in the list are generated by doing the following.
For each of the result of length n - 2 :
add 1 on its left and 1 on its right;
add 6 on its left and 9 on its right;
add 8 on its left and 8 on its right;
add 9 on its left and 6 on its right;
add 0 on its left and 0 on its right; (special case: 0 can not be added to either end when constructing the final result)

Recursive solution:
Runtime: The number of results in relation to n is 3 * 2^(n-1) for n >= 1 when n is odd;
5 * 2^(n-2) for n >=2 when n is even;
so the run time is exponential O(2^n). It is optimal since there are exponential number of solutions.

Space complexity: for odd n, 3 * (2^(n-1) + 2^(n-3) + .........+ 1 ) O(2^n);
similar when n is even.

 

public class Solution {
    public List<String> findStrobogrammatic(int n) {
        List<StringBuilder> sbList = findRecursive(n, n);
        List<String> ans = new ArrayList<>();
        for(StringBuilder sb: sbList) {
            ans.add(sb.toString());
        }
        return ans;
    }
    
    private List<StringBuilder> findRecursive(int currLen, int targetLen)
    {
        List<StringBuilder> r = new ArrayList<StringBuilder>();
        if(currLen == 0)
        {
            r.add(new StringBuilder(""));
            return r;
        }
        if(currLen == 1)
        {
            r.add(new StringBuilder("0"));
            r.add(new StringBuilder("1"));
            r.add(new StringBuilder("8"));
            return r;
        }
        
        List<StringBuilder> shorter = findRecursive(currLen - 2, targetLen);
        for(StringBuilder sb : shorter)
        {
            if(currLen != targetLen)
            {
                r.add(new StringBuilder("0").append(sb).append("0"));
            }
            r.add(new StringBuilder("1").append(sb).append("1"));
            r.add(new StringBuilder("6").append(sb).append("9"));
            r.add(new StringBuilder("8").append(sb).append("8"));
            r.add(new StringBuilder("9").append(sb).append("6"));
        }
        
        return r;
    }
}

 

Related Problems

[LeetCode] Strobogrammatic Number III

posted @ 2019-11-24 02:38  Review->Improve  阅读(221)  评论(0编辑  收藏  举报