标签:box nta ima first tor soft 12px turn empty
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).
dp[i] 以 s[i] 结尾的前缀子串有多少种解码方法
dp[i] = dp[i - 1] * 1 if s[i] != ‘0‘
dp[i] += dp[i - 2] * 1 if 10 <= int(s[i - 1..i]) <= 26
这里的关键还是由哪个元素过来的,然后定义好dp(i)的定义
参考
class Solution {
public int numDecodings(String s) {
int n = s.length();
if(n == 0) return 0;
if(s.charAt(0) == ‘0‘) return 0;
int[] dp = new int[n];
dp[0] = 1;
for(int i = 1; i < n; i++){
int first = s.charAt(i-1)-‘0‘;
int second = s.charAt(i)-‘0‘;
//从i-1过来,相等
if(second != 0){
dp[i] = dp[i-1];
}
//从i-2过来,保证两个数组合起来为合理的解码即可。这个时候相当于有两个分支,所以是加
int tmp = first*10+second;
if(tmp >= 10 && tmp <= 26){
if(i == 1)
dp[i] += 1;
else
dp[i] += dp[i-2];
}
}
return dp[n-1];
}
}
LeetCode 91 动态规划 Decode Ways 解码方法
标签:box nta ima first tor soft 12px turn empty
原文地址:https://www.cnblogs.com/muche-moqi/p/13111108.html