Leetcode 91. Decode Ways 路线解析 解题报告

1 解题思想

意思是原来二十六个字母,可以编码成数字,数字正好对应他们的顺序。

现在我只知道数字,问说有几种可能字母组成的方式

这道题只能不停的递归查找,回溯

2 原题

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.

3 AC解

public class Solution {
    //基本来说遇到0要特殊处理,0的dp和他之前两位的是一样的,并且要检查是否符合要求,
    //其他情况么,就是如果不能喝前一个树构成1-26的数组,那么dp就等于之前的位置,反之为之前两个位置之和
    public int numDecodings(String s) {
        if(s.length()==0 || s.charAt(0)== '0') return 0;
        int path[]=new int[s.length()];
        for(int i=0;i'0';
        int dp[]=new int[s.length()+1];
        dp[1]=1;
        dp[0]=1;
        for(int i=2;i<=path.length;i++){
            if(path[i-1]==0){
                if(path[i-2]*10+path[i-1]<10 || path[i-2]*10+path[i-1]>26 ) return 0;
                dp[i]=dp[i-2];
                continue;
            }
            dp[i]=dp[i-1];
            if(path[i-2]>0 && path[i-2]*10+path[i-1]<27 && path[i-2]*10+path[i-1]>9 )
                dp[i]+=dp[i-2];
        }
        return dp[path.length];

    }
}

你可能感兴趣的:(leetcode-java)