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 }
  • 相关阅读:
    hdu 1253
    poj 2531 Network Saboteur
    rwkj 1501 数据结构:图的DFS遍历
    rwkj 1306 素数========拓展
    nyist 91 阶乘之和
    nyist 65 另一种阶乘问题
    nyist 31 5个数求最值
    nyist 22 素数求和
    向量 vector
    字符串 统计 ,删除,连接,变换
  • 原文地址:https://www.cnblogs.com/lishiblog/p/5802477.html
Copyright © 2011-2022 走看看