-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathProblem_0115_connect.cc
64 lines (61 loc) · 1.24 KB
/
Problem_0115_connect.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
#include <string>
#include <vector>
using namespace std;
// @sa https://www.bilibili.com/video/BV1cg4y1o719/
class Solution
{
public:
int numDistinct1(string s, string t)
{
int n = s.length();
int m = t.length();
if (n < m)
{
return 0;
}
// dp[i][j]表示:
// s[前缀长度为i]的所有子序列中,有多少个等于t[前缀长度为j]
vector<vector<unsigned long long>> dp(n + 1, vector<unsigned long long>(m + 1));
for (int i = 0; i <= n; i++)
{
// 只有空字符串满足条件
dp[i][0] = 1;
}
for (int i = 1; i <= n; i++)
{
for (int j = 1; j <= m; j++)
{
// s[i-1] != t[j-1]
dp[i][j] = dp[i - 1][j];
if (s[i - 1] == t[j - 1])
{
dp[i][j] += dp[i - 1][j - 1];
}
}
}
return dp[n][m];
}
// 空间压缩
int numDistinct2(string s, string t)
{
int n = s.length();
int m = t.length();
if (n < m)
{
return 0;
}
vector<unsigned long long> dp(m + 1);
dp[0] = 1;
for (int i = 1; i <= n; i++)
{
for (int j = m; j >= 1; j--)
{
if (s[i - 1] == t[j - 1])
{
dp[j] += dp[j - 1];
}
}
}
return dp[m];
}
};