-
Notifications
You must be signed in to change notification settings - Fork 0
/
Problem_0091_numDecodings.cc
83 lines (76 loc) · 1.34 KB
/
Problem_0091_numDecodings.cc
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
80
81
82
83
#include <iostream>
#include <string>
#include <vector>
#include "UnitTest.h"
using namespace std;
class Solution
{
public:
// 递归
int process(string &s, int cur)
{
if (cur == s.length())
{
return 1;
}
if (s[cur] == '0')
{
return 0;
}
int ways = process(s, cur + 1);
if (cur + 1 == s.length())
{
return ways;
}
int num = (s[cur] - '0') * 10 + s[cur + 1] - '0';
if (num <= 26)
{
ways += process(s, cur + 2);
}
return ways;
}
int numDecodings(string s)
{
if (s.length() == 0)
{
return 0;
}
return process(s, 0);
}
// 递归改dp
int dp(string s)
{
int n = s.length();
vector<int> dp(n + 1);
dp[n] = 1;
for (int i = n - 1; i >= 0; i--)
{
if (s[i] != '0')
{
dp[i] += dp[i + 1];
if (i + 1 < n)
{
int num = (s[i] - '0') * 10 + s[i + 1] - '0';
dp[i] += num <= 26 ? dp[i + 2] : 0;
}
}
}
return dp[0];
}
};
void testNumDecodings()
{
Solution s;
EXPECT_EQ_INT(2, s.numDecodings("12"));
EXPECT_EQ_INT(3, s.numDecodings("226"));
EXPECT_EQ_INT(0, s.numDecodings("06"));
EXPECT_EQ_INT(2, s.dp("12"));
EXPECT_EQ_INT(3, s.dp("226"));
EXPECT_EQ_INT(0, s.dp("06"));
EXPECT_SUMMARY;
}
int main()
{
testNumDecodings();
return 0;
}