Skip to content

Commit 53fc96c

Browse files
authored
Update decode_ways.cpp
1 parent 38088bf commit 53fc96c

File tree

1 file changed

+38
-40
lines changed

1 file changed

+38
-40
lines changed
Lines changed: 38 additions & 40 deletions
Original file line numberDiff line numberDiff line change
@@ -1,43 +1,3 @@
1-
/*
2-
Given a string w/ only digits, return # ways to decode it (letter -> digit)
3-
Ex. s = "12" -> 2 (AB 1 2 or L 12), s = "226" -> 3 (2 26 or 22 6 or 2 2 6)
4-
5-
DP: At each digit, check validity of ones & tens, if valid add to # ways
6-
Recurrence relation: dp[i] += dp[i-1] (if valid) + dp[i-2] (if valid)
7-
8-
Time: O(n)
9-
Space: O(n)
10-
*/
11-
/*
12-
class Solution {
13-
public:
14-
int numDecodings(string s) {
15-
if (s[0] == '0') {
16-
return 0;
17-
}
18-
19-
int n = s.size();
20-
21-
vector<int> dp(n + 1);
22-
dp[0] = 1;
23-
dp[1] = 1;
24-
25-
for (int i = 2; i <= n; i++) {
26-
int ones = stoi(s.substr(i - 1, 1));
27-
if (ones >= 1 && ones <= 9) {
28-
dp[i] += dp[i - 1];
29-
}
30-
int tens = stoi(s.substr(i - 2, 2));
31-
if (tens >= 10 && tens <= 26) {
32-
dp[i] += dp[i - 2];
33-
}
34-
}
35-
36-
return dp[n];
37-
}
38-
};
39-
*/
40-
411
/*
422
Given a string w/ only digits, return # ways to decode it (letter -> digit)
433
Ex. s = "12" -> 2 (AB 1 2 or L 12), s = "226" -> 3 (2 26 or 22 6 or 2 2 6)
@@ -74,3 +34,41 @@ class Solution {
7434
return curr;
7535
}
7636
};
37+
38+
/*
39+
Given a string w/ only digits, return # ways to decode it (letter -> digit)
40+
Ex. s = "12" -> 2 (AB 1 2 or L 12), s = "226" -> 3 (2 26 or 22 6 or 2 2 6)
41+
42+
DP: At each digit, check validity of ones & tens, if valid add to # ways
43+
Recurrence relation: dp[i] += dp[i-1] (if valid) + dp[i-2] (if valid)
44+
45+
Time: O(n)
46+
Space: O(n)
47+
*/
48+
class Solution2 {
49+
public:
50+
int numDecodings(string s) {
51+
if (s[0] == '0') {
52+
return 0;
53+
}
54+
55+
int n = s.size();
56+
57+
vector<int> dp(n + 1);
58+
dp[0] = 1;
59+
dp[1] = 1;
60+
61+
for (int i = 2; i <= n; i++) {
62+
int ones = stoi(s.substr(i - 1, 1));
63+
if (ones >= 1 && ones <= 9) {
64+
dp[i] += dp[i - 1];
65+
}
66+
int tens = stoi(s.substr(i - 2, 2));
67+
if (tens >= 10 && tens <= 26) {
68+
dp[i] += dp[i - 2];
69+
}
70+
}
71+
72+
return dp[n];
73+
}
74+
};

0 commit comments

Comments
 (0)