zoukankan      html  css  js  c++  java
  • 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 an encoded message containing digits, determine the total number of ways to decode it.

    For example,
    Given encoded message "12", it could be decoded as "AB" (1 2) or "L" (12).

    The number of ways decoding "12" is 2.

    不用考虑开头是0的情况,题目不会给出这样的数据

    这题是动态规划的题,找出递推公式比较难。
    跟跳阶梯那个题挺像的。跳阶梯那个题的递推公式很好写出,这个题有点复杂,细节比较多。


    思路就是用一个数组来存当前这个位置到最后的解码数。当然也可以使用几个变量。
    这里从字符串后面往前推。

     第i个元素处,往后的可能性,当第i个元素单独编码,就是1种可能,剩下的元素有dp[i+1]种可能;当第i和i+1个元素符合要求,剩下元素有dp[i+2]中可能。

    大的公式就是:dp[i]=dp[i+1]+dp[i+2],这个前提是i元素自己符合要求(1,。9),而且i和i+1组成的数字也符合要求。当i和i+1组成的数字不符合要求时,dp[i]=dp[i+1]。这里没有考虑0的出现。当i出现0,dp[i]默认为0。因为它只有和前面的元素组成10,20才行,这样在前面i元素处,它的方法数就等于dp[i+2]

    因为要有初始数据,所以dp数组的长度应该比字符串长度大一。初始值为1.,

    class Solution {
        public int numDecodings(String s) {
           if(s==null||s.length()==0) return 0;
            int len=s.length();
           
            int[] dp=new int[len+1];
            dp[len]=1;
            dp[len-1]=s.charAt(len-1)!='0'?1:0;
            for(int i=len-2;i>=0;i--){
                if(s.charAt(i)=='0') continue;
                else {
                    dp[i]=((Integer.parseInt(s.substring(i,i+2))<=26))?dp[i+1]+dp[i+2]:dp[i+1];
                }
            }
            
            return dp[0];
        }
    }
  • 相关阅读:
    matlab中 数据保留有效位数
    matlab的m程序转执行文件exe
    MFC创建好的对话框如何移植到新程序中
    STM32 ADC转换时间
    MFC修改窗口无标题和标题信息,修改执执行文件图标
    兔子慢的原因
    core2.1独立布署,报错的原因。
    修复安卓的bug
    2018-11-21 ko.pureComputed的使用
    2018-11-17 js的this引起的血案
  • 原文地址:https://www.cnblogs.com/xiaolovewei/p/8228935.html
Copyright © 2011-2022 走看看