【发布时间】:2015-02-12 00:40:48
【问题描述】:
问题陈述: 给定一个数字序列,计算给定数字序列的可能解码次数。
例子:
12 给出 2:
“AB”和“L”
和
123 给出 3:
“ABC”、“LC”和“AW”
这是我的尝试:
import java.util.*;
public class decodingcount {
static int calls = 0;
static Map<Integer, String> codes = new HashMap<Integer, String>();
private static void construct(){
codes.put(1, "A");
codes.put(2, "B");
codes.put(3, "C");
codes.put(4, "D");
//..so on
}
private static int decode(String str, String built){
construct();
int n = str.length();
int count = 0;
if (n == 0) {
System.out.println(built);
return 1;
}
// If you have 0's, then they don't have a corresponding singular letter. Break off the recursion.
if (str.substring(0, 1).equals("0"))
return 0;
String x = codes.get(Integer.parseInt(str.substring(0, 1)));
if (x == null)
return 0;
count = decode(str.substring(1), built+x);
if (n > 1) {
// If it's more than 26, it doesn't have a corresponding letter. Break off the recursion.
if (Integer.parseInt(str.substring(0, 2)) > 26)
return 0;
String y = codes.get(Integer.parseInt(str.substring(0, 2)));
count += decode(str.substring(2), built+y);
}
return count;
}
public static void main(String[] args) {
System.out.println(decode(args[0], ""));
}
}
这在指数时间内运行。我真的很难将其转换为动态编程自下而上的制表算法。 Here is my attempt .它返回 0。不胜感激。
【问题讨论】:
-
对于什么输入,它给出 0 ?
-
如果输入字符串包含一个零,那么答案应该是零,你可能会给出一个诸如“1203”之类的输入,代码看起来不错
-
你有一个大错误。尽管有一个 0,
1203有一个解码,ATC。同样,456有一个解码,“DEF”,尽管有超过 26 的 2 个数字序列。 -
除了忽略零之外,如果您使用算法,我认为您可能希望在每次迭代时检查 i,i +1 和 i-1,i +1 子字符串,而不是 i,i+2。您还需要检查前两位数字以正确初始化 count[] 中的前两个值。
-
@sasha 如果我用 '1214' 调用它,我得到一个 0。
标签: java algorithm recursion dynamic-programming