-
Notifications
You must be signed in to change notification settings - Fork 28
/
Copy pathDecode_Ways.cpp
69 lines (63 loc) · 1.57 KB
/
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
59
60
61
62
63
64
65
66
67
68
69
class Solution {
public:
bool valid(string s) {
if (s.size() == 0) {
return false;
}
if (s[0] == '0') {
return false;
}
if (s.size() == 2) {
if (s[0] > '2' || (s[0] == '2' && s[1] > '6')) {
return false;
}
}
return true;
}
int numDecodingsUtil(string s, int indx, vector<int>& dp) {
if(indx == (int)s.length()) {
return 1;
}
if(dp[indx] != -1) {
return dp[indx];
}
int ret = 0;
if(s[indx] != '0') {
ret += numDecodingsUtil(s, indx + 1, dp);
}
if(indx + 1 < s.length() and valid(s.substr(indx, 2))) {
ret += numDecodingsUtil(s, indx + 2, dp);
}
return dp[indx] = ret;
}
int numDecodings(string s) {
if (s.empty()) {
return 0;
}
// recursive
// vector<int> dp(s.size(), -1);
// return numDecodingsUtil(s, 0, dp);
vector<int> dp(s.size(), 0);
if (s[0] != '0') {
dp[0] = 1;
}
if (s.size() == 1) {
return dp[0];
}
if (valid(s.substr(0, 2))) {
dp[1]++;
}
if (s[0] != '0' && s[1] != '0') {
dp[1]++;
}
for (int i = 2; i < s.size(); i++) {
if (s[i] != '0') {
dp[i] += dp[i - 1];
}
if (valid(s.substr(i - 1, 2))) {
dp[i] += dp[i - 2];
}
}
return dp[s.size() - 1];
}
};