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

    Solution:

     1 public class Solution {
     2     static char[] nums1 = new char[] { '0', '1', '8', '6', '9' };
     3     static char[] nums2 = new char[] { '0', '1', '8', '9', '6' };
     4 
     5     public List<String> findStrobogrammatic(int n) {
     6         List<String> res = new ArrayList<String>();
     7         StringBuilder builder = new StringBuilder();
     8         findStrobogrammaticRecur(n, builder, 1, res);
     9 
    10         return res;
    11     }
    12 
    13     public void findStrobogrammaticRecur(int n, StringBuilder builder, int curLevel, List<String> res) {
    14         if (curLevel > n / 2) {
    15             if (n % 2 == 1) {
    16                 // add one more char into front, no '6' or '9'
    17                 for (int i = 0; i < 3; i++) {
    18                     builder.insert(n / 2, nums1[i]);
    19                     res.add(builder.toString());
    20                     builder.deleteCharAt(n / 2);
    21                 }
    22             } else
    23                 res.add(builder.toString());
    24             return;
    25         }
    26 
    27         // if curLevel is n/2, we should skip '0'.
    28         int start = (curLevel == n/2) ? 1 : 0;
    29         for (int i = start; i < 5; i++) {
    30             builder.insert(0, nums1[i]);
    31             builder.append(nums2[i]);
    32             findStrobogrammaticRecur(n, builder, curLevel + 1, res);
    33             builder.deleteCharAt(0);
    34             builder.deleteCharAt(builder.length() - 1);
    35         }
    36     }
    37 }
  • 相关阅读:
    java 求 1!+2!+3!+....+10!的和为
    Java 循环控制语句
    java for 循环 九九乘法表
    Java for 循环
    Java while 和 do...while
    Java if语句
    Java switch 语句
    java a++ 和 ++a 理解
    Java 自动转换和强制转换
    二叉树遍历
  • 原文地址:https://www.cnblogs.com/lishiblog/p/5802477.html
Copyright © 2011-2022 走看看