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];
    }
}
原文地址:https://www.cnblogs.com/xiaolovewei/p/8228935.html