問題陳述: 給定一個數字序列,計算給定數字序列的可能解碼。將基本的遞歸算法轉換爲動態的自下而上列表算法
實例:
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? – sashas 2015-02-12 01:24:42
如果輸入字符串包含零,那麼答案應該是零,你可能會給出一個輸入,如「1203」,代碼對我來說很好 – sashas 2015-02-12 01:27:12
你有一個重大的錯誤。儘管有一個0,'1203'有一個解碼,'ATC'。同樣'456'解碼,'DEF',儘管有2個數字序列超過26. – btilly 2015-02-12 02:23:18