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.
The naive approach is use dfs:
suppose we have 1123456
the answer should be f(123456) + f(23456)
To improve the performance we could use memory to avoid repeating computation.
Code:
public class Solution {
public int numDecodings(String s) {
// start, end
if(s.equals("")) return 0;
HashMap<Integer,Integer> hm = new HashMap();
hm.put(s.length(),1);
return search(0,s,hm);
}
public int search(int start, String s, HashMap<Integer,Integer> hm){
if(hm.containsKey(start)){
return hm.get(start);
}
int i = s.charAt(start) - '0';
if(i == 0){
hm.put(start, 0);
return 0;
}
int ans = search(start + 1, s, hm);
if(start + 1 < s.length()){
i = i * 10 + s.charAt(start + 1) - '0';
if(i <= 26){
ans += search(start + 2, s, hm);
}
}
hm.put(start, ans);
return ans;
}
}The is actually the same using DP:
if(s[i] == '0') dp[i] = 0;
else{
DP[i] = DP[i + 1] + ((s[i]*10 + s[i + 1] <= 26) ? DP[i + 2] : 0)
数字解码算法
本文介绍了一种基于递归和动态规划的数字解码算法,该算法可以计算出给定数字字符串的不同解码方式的数量。例如,对于数字串“12”,它可以被解码为“AB”或“L”。文章通过具体实例解释了算法的工作原理,并提供了详细的实现代码。
293

被折叠的 条评论
为什么被折叠?



