LeetCode Strobogrammatic Number II

Posted Dylan_Java_NYC

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了LeetCode Strobogrammatic Number II相关的知识,希望对你有一定的参考价值。

原题链接在这里:https://leetcode.com/problems/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"].

题解:

base case 分奇数偶数两种. 拿到base case, 在每一个 string 前后加上"1", "1"; "8","8";...等等添加到新的res中去. 

corner case是若是string长度大于1, "0"不能加在最前面. 所以用 m != n搞定.

Time Complexity: O(5^n), exponential.

Space: O(n/2  + 5^(n/2)), n/2层stack, 5^(n/2)是当前base的大小.

AC Java:

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

跟上Strobogrammatic Number III.

类似Strobogrammatic Number.

以上是关于LeetCode Strobogrammatic Number II的主要内容,如果未能解决你的问题,请参考以下文章

[LeetCode] Strobogrammatic Number 对称数

Leetcode 246: Strobogrammatic Number

[LeetCode] Strobogrammatic Number III 对称数之三

[LeetCode] Strobogrammatic Number III

[LeetCode] 246. Strobogrammatic Number 对称数

[LeetCode] Strobogrammatic Number II