Leetcode: Strobogrammatic Number II

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://segmentfault.com/a/1190000003787462

找出所有的可能,必然是深度优先搜索。但是每轮搜索如何建立临时的字符串呢?因为数是“对称”的,我们插入一个字母就知道对应位置的另一个字母是什么,所以我们可以从中间插入来建立这个临时的字符串。这样每次从中间插入两个“对称”的字符,之前插入的就被挤到两边去了。这里有几个边界条件要考虑:

  1. 如果是第一个字符,即临时字符串为空时进行插入时,不能插入'0',因为没有0开头的数字

  2. 如果n=1的话,第一个字符则可以是'0'

  3. 如果只剩下一个带插入的字符,这时候不能插入'6'或'9',因为他们不能和自己产生映射,翻转后就不是自己了

这样,当深度优先搜索时遇到这些情况,则要相应的跳过

 1 public class Solution {
 2     
 3     char[] table = {'0', '1', '8', '6', '9'};
 4     List<String> res;
 5     
 6     public List<String> findStrobogrammatic(int n) {
 7         res = new ArrayList<String>();
 8         build(n, "");
 9         return res;
10     }
11     
12     public void build(int n, String tmp){
13         if(n == tmp.length()){
14             res.add(tmp);
15             return;
16         }
17         boolean last = n - tmp.length() == 1;
18         for(int i = 0; i < table.length; i++){
19             char c = table[i];
20             // 第一个字符不能为'0',但n=1除外。只插入一个字符时不能插入'6'和'9'
21             if((n != 1 && tmp.length() == 0 && c == '0') || (last && (c == '6' || c == '9'))){
22                 continue;
23             }
24             StringBuilder newTmp = new StringBuilder(tmp);
25             // 插入字符c和它的对应字符
26             append(last, c, newTmp);
27             build(n, newTmp.toString());
28         }
29     }
30     
31     public void append(boolean last, char c, StringBuilder sb){
32         if(c == '6'){
33             sb.insert(sb.length()/2, "69");
34         } else if(c == '9'){
35             sb.insert(sb.length()/2, "96");
36         } else {
37             sb.insert(sb.length()/2, last ? c : ""+c+c);
38         }
39     }
40 }

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值