Tuesday, August 4, 2015

LeetCode [247] Strobogrammatic Number II

247. Strobogrammatic Number II
Medium

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

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
class Solution {
    public List<String> findStrobogrammatic(int n) {
        return helper(n, n);
    }
    
    List<String> helper(int n, int N){
        List<String> list = new ArrayList<>();
        if(n==0){
            list.add("");   
        }else if(n==1){
            list.addAll(Arrays.asList("0","1", "8"));
        }else{
            List<String> tmp = helper(n-2, N);
            for(String s : tmp){
                list.addAll(Arrays.asList("1"+s+"1", "8"+s+"8", "6"+s+"9", "9"+s+"6"));
                if(n<N) list.add("0"+s+"0");
            }
        }
        return list;
    }
}

No comments:

Post a Comment