题目:
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"].
Hint:
- Try to use recursion and notice that it should recurse with n - 2 instead of n - 1.
链接: http://leetcode.com/problems/strobogrammatic-number-ii/
题解:
求所有长度为n的strobogrammatic number。这题一开始的思路是用DFS + Backtracking。还要处理一些特殊的边界条件,比如n的长度为奇数和偶数,以及最外层不能为两个'0'等等,代码写得很拖沓。 Discuss区有不少好的代码,二刷时一定要思考清楚再进行优化。这里我主要是从中心向两边添加,而discuss区大家大部分都是从两边向中心递归,所以我的代码还需要回溯,不够简练。
Time Complexity - O(2n), Space Complexity - O(n)。
public class Solution {
public List<String> findStrobogrammatic(int n) {
if(n < 1)
return new ArrayList<String>();
List<String> res = new ArrayList<>();
Map<Character, Character> map = new HashMap<>();
map.put('0', '0');
map.put('1', '1');
map.put('6', '9');
map.put('8', '8');
map.put('9', '6');
StringBuilder sb = new StringBuilder();
int position = (n % 2 == 0) ? 0 : 1;
findStrobogrammatic(res, sb, map, n, position);
return res;
}
private void findStrobogrammatic(List<String> res, StringBuilder sb, Map<Character, Character> map, int n, int position) {
if(sb.length() > n)
return;
if(sb.length() == n) {
res.add(sb.toString());
return;
}
if(position == 1) {
for(char c : map.keySet()) {
if(c == '6' || c == '9')
continue;
sb.append(c);
findStrobogrammatic(res, sb, map, n, position + 1);
sb.setLength(0);
}
} else {
for(char c : map.keySet()) {
if(n - sb.length() == 2 && c == '0')
continue;
sb.insert(0, c);
sb.append(map.get(c));
findStrobogrammatic(res, sb, map, n, position + 2);
sb.deleteCharAt(0);
sb.deleteCharAt(sb.length() - 1);
}
}
}
}
二刷:
两种思路:
- 和一刷一样,用dfs + backtracking
- 求一半String的permutation,剪去一些invalid case,再补上另外一半。也就是使用跟267. Palindrome Permutation II类似的方法。
Java:
Reference:
https://leetcode.com/discuss/50412/ac-clean-java-solution
https://leetcode.com/discuss/50377/my-concise-java-solution-using-dfs
https://leetcode.com/discuss/52277/accepted-java-solution-using-recursion
https://leetcode.com/discuss/53144/my-concise-iterative-java-code
https://leetcode.com/discuss/68215/simple-java-solution-without-recursion
来源:https://www.cnblogs.com/yrbbest/p/5008994.html