|
1 | 1 | package com.fishercoder.solutions;
|
2 | 2 |
|
| 3 | +import java.util.HashMap; |
| 4 | +import java.util.Map; |
| 5 | + |
3 | 6 | public class _91 {
|
4 | 7 | /**
|
5 | 8 | * Credit: https://discuss.leetcode.com/topic/35840/java-clean-dp-solution-with-explanation
|
@@ -31,4 +34,40 @@ public int numDecodings(String s) {
|
31 | 34 | return dp[s.length()];
|
32 | 35 | }
|
33 | 36 | }
|
| 37 | + |
| 38 | + public static class Solution2 { |
| 39 | + /**credit: https://leetcode.com/problems/decode-ways/solution/ |
| 40 | + * Approach 1: Recursive Approach with Memoization |
| 41 | + * |
| 42 | + * The actual code goes from the right most character to the left side to build out the dp cache map. |
| 43 | + * And this HashMap uses index as its key instead of a substring. |
| 44 | + * */ |
| 45 | + |
| 46 | + public int numDecodings(String s) { |
| 47 | + return dp(new HashMap<>(), s, 0); |
| 48 | + } |
| 49 | + |
| 50 | + private int dp(Map<Integer, Integer> cache, String s, int index) { |
| 51 | + if (cache.containsKey(index)) { |
| 52 | + return cache.get(index); |
| 53 | + } |
| 54 | + if (index == s.length()) { |
| 55 | + //this means we reached the end of the string, so return 1 as success |
| 56 | + return 1; |
| 57 | + } |
| 58 | + if (s.charAt(index) == '0') { |
| 59 | + //this means this string cannot be decoded |
| 60 | + return 0; |
| 61 | + } |
| 62 | + if (index == s.length() - 1) { |
| 63 | + return 1; |
| 64 | + } |
| 65 | + int ways = dp(cache, s, index + 1); |
| 66 | + if (Integer.parseInt(s.substring(index, index + 2)) <= 26) { |
| 67 | + ways += dp(cache, s, index + 2); |
| 68 | + } |
| 69 | + cache.put(index, ways); |
| 70 | + return cache.get(index); |
| 71 | + } |
| 72 | + } |
34 | 73 | }
|
0 commit comments