File tree Expand file tree Collapse file tree 1 file changed +39
-1
lines changed
cpp/neetcode_150/13_1-d_dynamic_programming Expand file tree Collapse file tree 1 file changed +39
-1
lines changed Original file line number Diff line number Diff line change 8
8
Time: O(n)
9
9
Space: O(n)
10
10
*/
11
-
11
+ /*
12
12
class Solution {
13
13
public:
14
14
int numDecodings(string s) {
@@ -36,3 +36,41 @@ class Solution {
36
36
return dp[n];
37
37
}
38
38
};
39
+ */
40
+
41
+ /*
42
+ Given a string w/ only digits, return # ways to decode it (letter -> digit)
43
+ Ex. s = "12" -> 2 (AB 1 2 or L 12), s = "226" -> 3 (2 26 or 22 6 or 2 2 6)
44
+
45
+ DP: Bottom-up approach: check if zero and assign the i+1 value to the current;
46
+ otherwise, check if the current char is a '1' and thus admits any i+1 char,
47
+ or a '2', which admits only 0 <= x <= 6 as characters at i+1.
48
+
49
+ Time: O(n)
50
+ Space: O(1)
51
+ */
52
+ class Solution {
53
+ public:
54
+ int numDecodings (string s) {
55
+ int n = s.size ();
56
+ int prev = 0 ;
57
+ int curr = 1 ;
58
+
59
+ for (int i = n - 1 ; i >= 0 ; --i){
60
+ int newCurr;
61
+ if (s[i] == ' 0' )
62
+ newCurr = 0 ;
63
+ else
64
+ newCurr = curr;
65
+
66
+ if (i + 1 < n && (s[i] == ' 1' || s[i] == ' 2'
67
+ && s[i+1 ] <= ' 6' ))
68
+ newCurr += prev;
69
+
70
+ prev = curr;
71
+ curr = newCurr;
72
+ }
73
+
74
+ return curr;
75
+ }
76
+ };
You can’t perform that action at this time.
0 commit comments