问题描述

问题分析
- 将给定数字字符串译码成字母字符串,看能有多少种译码情况
- 和 LeetCode 62. Unique Paths 类似,是统计可能性情况个数类型的题目,先从递归入手,然后想动态规划。
- 译码情况的问题,要注意,当前可能译一个,也可能译两个,也可能遇到‘0’,直接译码失败,这些都要考虑。
代码实现
public int numDecodings(String s) {
if (s == null ) {
return 0;
}
char[] chs = s.toCharArray();
return getNum(chs, 0);
}
public int getNum(char[] chs, int begin) {
if (begin == chs.length) {
return 1;
}
if (chs[begin] == '0') {
return 0;
}
int res = 0;
res += getNum(chs, begin + 1);
if (begin + 1 < chs.length && (chs[begin] - '0') * 10 + chs[begin + 1] - '0' <= 26) {
res += getNum(chs, begin + 2);
}
return res;
}
public int numDecodings(String s) {
if (s == null ) {
return 0;
}
char[] chs = s.toCharArray();
int[] dp = new int[chs.length + 1];
dp[chs.length] = 1;
for (int i = chs.length - 1; i >= 0; --i) {
if (chs[i] == '0') {
dp[i] = 0;
continue;
}
dp[i] = dp[i + 1];
if (i + 1 < chs.length && (chs[i] - '0') * 10 + chs[i + 1] - '0' <= 26) {
dp[i] += dp[i + 2];
}
}
return dp[0];
}