• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
neverlandly
博客园    首页    新随笔    联系   管理    订阅  订阅

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.

Watch out for cornor case:

when n = 2, there shouldn't be "00" returned.

but when n = 4, which uses n =2 as recursion base, "1001" is an answer

 1 class Solution {
 2     public List<String> findStrobogrammatic(int n) {
 3         return helper(n, n);
 4     }
 5     
 6     public List<String> helper(int n, int limit) {
 7         if (n <= 0) return Arrays.asList("");
 8         if (n == 1) return Arrays.asList("0", "1", "8");
 9         
10         List<String> list = helper(n - 2, limit);
11         
12         List<String> res = new ArrayList<>();
13         
14         for (String str : list) {
15             if (n != limit) {
16                 res.add("0" + str + "0");
17             }
18             res.add("1" + str + "1");
19             res.add("6" + str + "9");
20             res.add("9" + str + "6");
21             res.add("8" + str + "8");
22         }
23         return res;
24     }
25 }

 

posted @ 2015-12-21 09:30  neverlandly  阅读(310)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3