zoukankan      html  css  js  c++  java
  • LeetCode 247. 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.

  • 相关阅读:
    Linux用户、用户组、文件权限设置
    spring,springMvc和mybatis整合配置
    spring,springMvc和hibernate整合
    spring与mybatis
    spring与Dbcp
    初识事物
    spring与Aop
    初识spring
    mysql 完整性约束
    mysql数据库的基本操作
  • 原文地址:https://www.cnblogs.com/Dylan-Java-NYC/p/5244042.html
Copyright © 2011-2022 走看看