My code:
public class Solution {
private int counter = 0;
public int strobogrammaticInRange(String low, String high) {
char[][] pairs = new char[][]{{'0', '0'}, {'1', '1'}, {'6', '9'}, {'8', '8'}, {'9', '6'}};
for (int i = low.length(); i <= high.length(); i++) {
helper(0, i - 1, new char[i], pairs, low, high);
}
return counter;
}
private void helper(int begin, int end, char[] board, char[][] pairs, String low, String high) {
if (begin > end) {
String s = String.valueOf(board);
if (s.length() == low.length() && s.compareTo(low) < 0) {
return;
}
else if (s.length() == high.length() && s.compareTo(high) > 0) {
return;
}
else {
counter++;
}
}
else if (begin == end) {
board[begin] = '0';
helper(begin + 1, end - 1, board, pairs, low, high);
board[begin] = '1';
helper(begin + 1, end - 1, board, pairs, low, high);
board[begin] = '8';
helper(begin + 1, end - 1, board, pairs, low, high);
}
else {
for (int i = 0; i < pairs.length; i++) {
char x = pairs[i][0];
char y = pairs[i][1];
if (begin == 0 && x == '0') {
continue;
}
board[begin] = x;
board[end] = y;
helper(begin + 1, end - 1, board, pairs, low, high);
}
}
}
public static void main(String[] args) {
Solution test = new Solution();
int ret = test.strobogrammaticInRange("50", "100");
System.out.println(ret);
}
}
reference:
https://discuss.leetcode.com/topic/31386/easiest-20ms-94-java-solution
一開始我想的是崎弃,能不能直接窮舉出來。
但是發(fā)現(xiàn)不太容易,于是看答案隙姿。發(fā)現(xiàn)所看的答案亥揖,也是拿 II 作為基礎(chǔ)烛亦,把 長度 [low.length(), high.length()] 的可能找出來坝咐,然后刪去那些超出范圍的铃剔。
當然撒桨,整個過程可以更加優(yōu)化。使得空間復雜度一直保持在 O(high.length())
Anyway, Good luck, Richardo! -- 09/22/2016