forked from varunu28/LeetCode-Java-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDecode Ways.java
More file actions
58 lines (44 loc) · 1.38 KB
/
Decode Ways.java
File metadata and controls
58 lines (44 loc) · 1.38 KB
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
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
class Solution {
int[] memo;
public int numDecodings(String s) {
if (s.length() == 0) {
return 0;
}
memo = new int[s.length() + 1];
Arrays.fill(memo, -1);
return helperDp(0, s);
}
private int helperDp(int idx, String s) {
if (memo[idx] > -1) {
return memo[idx];
}
int n = s.length();
if (idx == n) {
return memo[idx] = 1;
}
if (s.charAt(idx) == '0') {
return memo[idx] = 0;
}
int temp = helperRecursive(idx + 1, s);
memo[idx + 1] = temp;
if (idx < n - 1 && (s.charAt(idx) == '1' || (s.charAt(idx) == '2' && s.charAt(idx + 1) < '7'))) {
memo[idx + 2] = helperRecursive(idx + 2, s);
temp += memo[idx + 2];
}
return temp;
}
private int helperRecursive(int idx, String s) {
int n = s.length();
if (idx == n) {
return 1;
}
if (s.charAt(idx) == '0') {
return 0;
}
int temp = helperRecursive(idx + 1, s);
if (idx < n - 1 && (s.charAt(idx) == '1' || (s.charAt(idx) == '2' && s.charAt(idx + 1) < '7'))) {
temp += helperRecursive(idx + 2, s);
}
return temp;
}
}