• 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 }
  • 相关阅读:
    【转】 上海交大ACM队长建议
    好资源
    待做
    分治思想
    周末看的东西
    [UVa11988] Broken Keyboard (a.k.a. Beiju Text)
    UVa 题目分类
    [UVa11729] Commando War
    [LA3135] Arugus
    [UVa11995] I Can Guess the Data Structure!
  • 原文地址:https://www.cnblogs.com/lishiblog/p/5802477.html
Copyright © 2020-2023  润新知