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"]
.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65
| public class Solution { private char[] validNumbers = new char[]{'0', '1', '6', '8', '9'}; private char[] singleable = new char[]{'0', '1', '8'};
public List<String> findStrobogrammatic(int n) { assert n > 0; List<String> result = new ArrayList<>();
if (n == 1) { for (char c : singleable) { result.add(String.valueOf(c)); } return result; }
if (n % 2 == 0) { helper(n, new StringBuilder(), result); } else { helper(n - 1, new StringBuilder(), result); List<String> tmp = new ArrayList<>(); for (String s : result) { for (char c : singleable) { tmp.add(new StringBuilder(s).insert(s.length() / 2, c).toString()); } } result = tmp; } return result; }
private void helper(int n, StringBuilder sb, List<String> result) { if (sb.length() > n) return;
if (sb.length() == n) { if (sb.length() > 0 && sb.charAt(0) != '0') { result.add(sb.toString()); } return; }
for (char c : validNumbers) { StringBuilder tmp = new StringBuilder(sb); String s = "" + c + findMatch(c); tmp.insert(tmp.length() / 2, s); helper(n, tmp, result); } }
private char findMatch(char c) { switch (c) { case '1': return '1'; case '6': return '9'; case '9': return '6'; case '8': return '8'; case '0': return '0'; default: return 0; } } }
|