zoukankan      html  css  js  c++  java
  • 19.2.23 [LeetCode 91] Decode Ways

    A message containing letters from A-Z is being encoded to numbers using the following mapping:

    'A' -> 1
    'B' -> 2
    ...
    'Z' -> 26
    

    Given a non-empty string containing only digits, determine the total number of ways to decode it.

    Example 1:

    Input: "12"
    Output: 2
    Explanation: It could be decoded as "AB" (1 2) or "L" (12).
    

    Example 2:

    Input: "226"
    Output: 3
    Explanation: It could be decoded as "BZ" (2 26), "VF" (22 6), or "BBF" (2 2 6).

    题意

    输出一串数字可能的解读方式,这串数字的解读只能由1~26组成

    题解

    记忆性递归,好像挺慢的

     1 class Solution {
     2 public:
     3     vector<int>mark;
     4     int cnt(string s) {
     5         int one = s[0] - '0', two = 0, ans = 0, l = s.length();
     6         if (one == 0)return 0;
     7         if (mark[l] != -1)return mark[l];
     8         if (l > 1)two = one * 10 + s[1] - '0';
     9         else if (l == 0)return 1;
    10         ans += cnt(s.substr(1));
    11         if (two <= 26 && two >= 1)
    12             ans += cnt(s.substr(2));
    13         mark[l] = ans;
    14         return ans;
    15     }
    16     int numDecodings(string s) {
    17         int l = s.length();
    18         mark = vector<int>(l + 1, -1);
    19         return cnt(s);
    20     }
    21 };
    View Code

    于是dp,o(n)的

     1 class Solution {
     2 public:
     3     int numDecodings(string s) {
     4         int l = s.length();
     5         vector<int>dp(l + 1, 0);
     6         dp[0] = 1;
     7         if (s[0] - '0' != 0)dp[1] = 1;
     8         for (int i = 1; i < l; i++) {
     9             int one = s[i - 1] - '0', two = (s[i] - '0') + one * 10;
    10             if (one != 0 && two <= 26 && two >= 1)
    11                 dp[i+1] +=dp[i - 1];
    12             if(s[i]!='0')
    13                 dp[i+1] += dp[i];
    14         }
    15         return dp[l];
    16     }
    17 };
    View Code
  • 相关阅读:
    使用vue来开发一个下拉菜单组件(2)
    使用vue来开发一个下拉菜单组件(1)
    在Vue中引入Bootstrap,Font-awesome
    九宫格表格样式
    web upload 上传多张图片实例
    input 的multiple 上传多个文件
    常用 验证码 JS 代码
    最全 H5 form 表单 + 正则验证
    mysql的指令
    Ant编译MapReduce程序
  • 原文地址:https://www.cnblogs.com/yalphait/p/10423833.html
Copyright © 2011-2022 走看看