|
4 | 4 | import java.util.Arrays;
|
5 | 5 | import java.util.List;
|
6 | 6 |
|
7 |
| -/** |
8 |
| - * A strobogrammatic number is a number that looks the same when rotated 180 degrees (looked at upside down). |
9 |
| -
|
10 |
| - Find all strobogrammatic numbers that are of length = n. |
11 |
| -
|
12 |
| - For example, |
13 |
| - Given n = 2, return ["11","69","88","96"]. |
14 |
| -
|
15 |
| - Hint: |
16 |
| -
|
17 |
| - Try to use recursion and notice that it should recurse with n - 2 instead of n - 1. |
18 |
| - */ |
19 | 7 | public class _247 {
|
20 |
| - public List<String> findStrobogrammatic(int n) { |
21 |
| - return recursiveHelper(n, n); |
22 |
| - } |
23 |
| - |
24 |
| - private List<String> recursiveHelper(int n, int m) { |
25 |
| - if (n == 0) { |
26 |
| - return new ArrayList<>(Arrays.asList("")); |
27 |
| - } |
28 |
| - if (n == 1) { |
29 |
| - return new ArrayList<>(Arrays.asList("0", "1", "8")); |
| 8 | + public static class Solution1 { |
| 9 | + public List<String> findStrobogrammatic(int n) { |
| 10 | + return recursiveHelper(n, n); |
30 | 11 | }
|
31 | 12 |
|
32 |
| - List<String> list = recursiveHelper(n - 2, m); |
33 |
| - List<String> res = new ArrayList<String>(); |
| 13 | + private List<String> recursiveHelper(int n, int m) { |
| 14 | + if (n == 0) { |
| 15 | + return new ArrayList<>(Arrays.asList("")); |
| 16 | + } |
| 17 | + if (n == 1) { |
| 18 | + return new ArrayList<>(Arrays.asList("0", "1", "8")); |
| 19 | + } |
34 | 20 |
|
35 |
| - for (int i = 0; i < list.size(); i++) { |
36 |
| - String s = list.get(i); |
37 |
| - if (n != m) { |
38 |
| - res.add("0" + s + "0"); |
| 21 | + List<String> list = recursiveHelper(n - 2, m); |
| 22 | + List<String> res = new ArrayList<>(); |
| 23 | + |
| 24 | + for (int i = 0; i < list.size(); i++) { |
| 25 | + String s = list.get(i); |
| 26 | + if (n != m) { |
| 27 | + res.add("0" + s + "0"); |
| 28 | + } |
| 29 | + res.add("1" + s + "1"); |
| 30 | + res.add("6" + s + "9"); |
| 31 | + res.add("8" + s + "8"); |
| 32 | + res.add("9" + s + "6"); |
39 | 33 | }
|
40 |
| - res.add("1" + s + "1"); |
41 |
| - res.add("6" + s + "9"); |
42 |
| - res.add("8" + s + "8"); |
43 |
| - res.add("9" + s + "6"); |
| 34 | + return res; |
44 | 35 | }
|
45 |
| - return res; |
46 | 36 | }
|
47 | 37 | }
|
0 commit comments