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
一开始我想的是,能不能直接穷举出来。
但是发现不太容易,于是看答案。发现所看的答案,也是拿 II 作为基础,把 长度 [low.length(), high.length()] 的可能找出来,然后删去那些超出范围的。
当然,整个过程可以更加优化。使得空间复杂度一直保持在 O(high.length())
Anyway, Good luck, Richardo! -- 09/22/2016
网友评论