1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38
| class Solution { public int numDecodings(String s) { Map<Integer, Integer> startIndexToCountMap = new HashMap<>(); return dfs(startIndexToCountMap, s, 0); }
private int dfs(Map<Integer, Integer> startIndexToCountMap, String s, int i) { if (i == s.length()) { return 1; }
Integer cached = startIndexToCountMap.get(i); if (cached != null) { return cached; }
int count = 0; char a = s.charAt(i); if (a == '0') { } else if (a == '1') { count += dfs(startIndexToCountMap, s, i + 1); if (i + 1 < s.length()) { count += dfs(startIndexToCountMap, s, i + 2); } } else if (a == '2') { count += dfs(startIndexToCountMap, s, i + 1); if (i + 1 < s.length() && s.charAt(i + 1) <= '6') { count += dfs(startIndexToCountMap, s, i + 2); } } else { count = dfs(startIndexToCountMap, s, i + 1); }
startIndexToCountMap.put(i, count); return count; } }
|