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"].
[分析]
实现2参考[url]https://leetcode.com/discuss/50412/ac-clean-java-solution[/url],
看这么清爽的代码真是让人赏心悦目~
实现2的思路就是从中间往两端扩展,自己的实现1思路是从两端往中间扩展,注意两端不能为0.
Find all strobogrammatic numbers that are of length = n.
For example,
Given n = 2, return ["11","69","88","96"].
[分析]
实现2参考[url]https://leetcode.com/discuss/50412/ac-clean-java-solution[/url],
看这么清爽的代码真是让人赏心悦目~
实现2的思路就是从中间往两端扩展,自己的实现1思路是从两端往中间扩展,注意两端不能为0.
public class Solution {
// Method 2
public List<String> findStrobogrammatic(int n) {
return helper(n, n);
}
public List<String> helper(int n, int m) {
if (n == 0) return new ArrayList<String>(Arrays.asList(""));
if (n == 1) return new ArrayList<String>(Arrays.asList("0", "1", "8"));
List<String> list = helper(n - 2, m);
List<String> ret = new ArrayList<String>();
for (String s : list) {
if (n != m) ret.add("0" + s + "0");
ret.add("1" + s + "1");
ret.add("8" + s + "8");
ret.add("6" + s + "9");
ret.add("9" + s + "6");
}
return ret;
}
// Method 1
char[] cand = {'0', '1', '8', '6', '9'};
public List<String> findStrobogrammatic1(int n) {
List<String> ret = new ArrayList<String>();
if (n <= 0) return ret;
recur(new char[n], 0, n - 1, ret);
return ret;
}
public void recur(char[] item, int i, int j, List<String> ret) {
if (i > j) {
ret.add(new String(item));
return;
} else if (i == j) {
for (int k = 0; k < 3; k++) {
item[i] = cand[k];
ret.add(new String(item));
}
return;
} else {
int start = i == 0 ? 1 : 0;
for (int k = start; k < 5; k++) {
if (k < 3) {
item[i] = item[j] = cand[k];
} else if (k == 3) {
item[i] = '6'; item[j] = '9';
} else {
item[i] = '9'; item[j] = '6';
}
recur(item, i + 1, j - 1, ret);
}
}
}
}