LeetCode: Strobogrammatic Number II

/**
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.
*/
import java.util.*;
public class StrobogrammaticNumberII{

public static List<String> findStro(int n){
List<String> res = new ArrayList<>();
int curlen = n, len = n;
helper(res, curlen, len);
return res;
}

static void helper(List<String> res, int curlen, int len){
if(curlen==0){
res.add("");
return;
}
if(curlen==1){
res.add("1");
res.add("8");
res.add("0");
return;
}
helper(res, curlen-2, len);
int size = res.size();
int i = 0;
while(i<size){
String cur = res.get(i);
//if we reached the end, then we cannot have 0s at the starting and end
if(curlen!=len){
res.add("0"+cur+"0");
}
res.add("1"+cur+"1");
res.add("8"+cur+"8");
res.add("6"+cur+"9");
res.add("9"+cur+"6");
size--;
res.remove(0);//remove the previous shorter strobogrammatic numbers after using them to build longer ones
}

}

public static void main(String[] args){
int n = 2;
System.out.println(Arrays.toString(findStro(n).toArray()));
System.out.println(Arrays.toString(findStro(1).toArray()));
System.out.println(Arrays.toString(findStro(3).toArray()));
}

}

No comments:

Post a Comment