-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy path91-decode-ways.cpp
58 lines (53 loc) · 1.72 KB
/
91-decode-ways.cpp
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
// DP with memo
// class Solution {
// public:
// int numDecodings(string s) {
// int len = s.size();
// auto ok = [](auto x) { return 1 <= x && x <= 26; };
// unordered_map<int, int> bag;
// function<int(int)> go = [&](int index) {
// if (bag.count(index)) return bag[index];
// if (index == len) return 1;
// auto one = s[index] - '0';
// auto two = (one && (index + 1) < len) ? stoi(s.substr(index, 2)) : 0;
// return bag[index] = (ok(one) ? go(index+1): 0) + (ok(two) ? go(index+2): 0);
// };
// return go(0);
// }
// };
// Iterative DP
// class Solution {
// public:
// int numDecodings(string s) {
// int len = s.size();
// auto ok = [](auto x) { return 1 <= x && x <= 26; };
// vector<int> dp(len + 1); dp[len] = 1;
// for (int i {len - 1}; i >= 0; i--) {
// auto one = s[i] - '0';
// auto two = one && i + 1 < len ? stoi(s.substr(i, 2)): 0;
// if (ok(one)) dp[i] += dp[i+1];
// if (ok(two)) dp[i] += dp[i+2];
// }
// return dp[0];
// }
// };
// constant space
// Iterative DP
class Solution {
public:
int numDecodings(string s) {
int len = s.size();
auto ok = [](auto x) { return 1 <= x && x <= 26; };
int first = 1, second = 0;
for (int i {len - 1}; i >= 0; i--) {
auto one = s[i] - '0';
auto two = one && i + 1 < len ? stoi(s.substr(i, 2)): 0;
int sum = 0;
if (ok(one)) sum = first;
if (ok(two)) sum += second;
second = first;
first = sum;
}
return first;
}
};