和strobogrammatic II一个做法。 算出range是几位数到几位数,比如50-100是2-3位,generate所有2和3位的所有可能,看看是不是在50-100之内,是的话res++...
public class Solution {
int res = 0;
public int strobogrammaticInRange(String low, String high) {
char[] ch1 = {'1','8','0','6','9'};
char[] ch2 = {'1','8','0','9','6'};
for (int i = low.length(); i<= high.length(); i++) {
char[] s = new char[i];
dfs(ch1, ch2, s, low, high, 0);
}
return res;
}
public void dfs(char[] ch1, char[] ch2, char[] s, String low, String high, int l) {
int r = s.length - 1 - l;
if (l > r) {
if (Long.valueOf(String.valueOf(s)) <= Long.valueOf(high) &&
Long.valueOf(String.valueOf(s)) >= Long.valueOf(low)) {
res++;
}
} else if (r == l) {
for (int i = 0; i < 3; i++) {
s[l] = ch1[i];
dfs(ch1, ch2, s, low, high, l + 1);
}
} else {
for (int i = 0; i < 5; i++) {
if (i == 2 && l == 0) continue;
s[l] = ch1[i];
s[r] = ch2[i];
dfs(ch1, ch2, s, low, high, l + 1);
}
}
}
}