-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdistinct-subsequences_2(AC).cpp
62 lines (56 loc) · 1.03 KB
/
distinct-subsequences_2(AC).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
// 1AC, spatially optimized version
#include <cstring>
#include <vector>
using namespace std;
class Solution {
public:
int numDistinct(string S, string T) {
int **dp;
int ls, lt;
int result;
int i, j;
ls = (int)S.size();
lt = (int)T.size();
if (ls == 0 || lt == 0 || ls < lt) {
return 0;
}
dp = new int*[2];
for (i = 0; i < 2; ++i) {
dp[i] = new int[lt + 1];
}
for (i = 0; i < 2; ++i) {
for (j = 0; j <= lt; ++j) {
dp[i][j] = 0;
}
}
if (S[0] == T[0]) {
dp[1][1] = 1;
}
int flag;
flag = 0;
for (i = 2; i <= ls; ++i) {
dp[flag][0] = 0;
if (S[i - 1] == T[0]) {
dp[flag][1] = dp[!flag][1] + 1;
} else {
dp[flag][1] = dp[!flag][1];
}
for (j = 2; j <= lt; ++j) {
if (S[i - 1] == T[j - 1]) {
dp[flag][j] = dp[!flag][j] + dp[!flag][j - 1];
} else {
dp[flag][j] = dp[!flag][j];
}
}
flag = !flag;
}
flag = !flag;
result = dp[flag][lt];
for (i = 0; i < 2; ++i) {
delete[] dp[i];
}
delete[] dp;
dp = NULL;
return result;
}
};