-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathDecode_Ways.cpp
More file actions
79 lines (60 loc) · 1.75 KB
/
Decode_Ways.cpp
File metadata and controls
79 lines (60 loc) · 1.75 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
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
// https://leetcode.com/problems/decode-ways/
// Bottom-up DP
class Solution {
public:
bool isValid(string &s, int ones, int tens)
{
if(tens != -1 && s[tens] == '0')
return false;
int num = s[ones] - '0';
if(tens != -1)
num += 10 * (s[tens] - '0');
return ((num >= 1) && (num <= 26));
}
int numDecodings(string s)
{
int n = s.length();
vector <int> dp(n+1, 0);
dp[0] = 1;
dp[1] = (s[0] == '0') ? 0 : 1;
for(int index = 2; index <= n; index++)
{
if(isValid(s, index-1, -1))
dp[index] += dp[index-1];
if(isValid(s, index-1, index-2))
dp[index] += dp[index-2];
}
return dp[n];
}
};
//Top-down DP
class Solution {
public:
bool isValid(string &s, int ones, int tens)
{
if(tens != -1 && s[tens] == '0')
return false;
int num = s[ones] - '0';
if(tens != -1)
num += 10 * (s[tens] - '0');
return ((num >= 1) && (num <= 26));
}
int decodeWays(string &s, int index, vector <int> &dp)
{
if(index == 0)
return 1;
if(dp[index] != -1)
return dp[index];
int ways = 0;
if(index-1 >= 0 && isValid(s, index-1, -1))
ways += decodeWays(s, index-1, dp);
if(index-2 >= 0 && isValid(s, index-1, index-2))
ways += decodeWays(s, index-2, dp);
return dp[index] = ways;
}
int numDecodings(string s)
{
vector <int> dp(s.length()+1, -1);
return decodeWays(s, s.length(), dp);
}
};