-
Notifications
You must be signed in to change notification settings - Fork 0
/
Distinct occurrences.cpp
132 lines (109 loc) · 2.54 KB
/
Distinct occurrences.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
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
// RECURSION (TLE)
class Solution
{
public:
int help(string& s,string& t,int i,int j)
{
//base case
if(j>=t.length())
return 1;
if(i>=s.length())
return 0;
//recursive calls
//and small calculation
int b=0;
int a=help(s,t,i+1,j);
if(s[i]==t[j])
b=help(s,t,i+1,j+1);
return (a+b);
}
int subsequenceCount(string s, string t)
{
return help(s,t,0,0);
}
};
// Memoization
int mod=1e9+7;
class Solution
{
public:
int help(string& s,string& t,int i,int j,vector<vector<int>>& memo)
{
//base case
if(j>=t.length())
return 1;
if(i>=s.length())
return 0;
//memo check
if(memo[i][j]!=-1)
return memo[i][j];
//recursive calls
//and small calculation
int b=0;
int a=help(s,t,i+1,j,memo);
if(s[i]==t[j])
b=help(s,t,i+1,j+1,memo);
return memo[i][j]=(a+b)%mod;
}
int subsequenceCount(string s, string t)
{
vector<vector<int>> memo(s.length(),vector<int>(t.length(),-1));
return help(s,t,0,0,memo);
}
};
// Tabulation
int mod=1e9+7;
class Solution
{
public:
int subsequenceCount(string s, string t)
{
int n=s.length();
int m=t.length();
vector<vector<int>> dp(n+1,vector<int>(m+1,0));
for(int i=0;i<=n;i++)
dp[i][t.length()]=1;
for(int i=n-1;i>=0;i--)
{
for(int j=0;j<m;j++)
{
int a,b;
a=b=0;
a=dp[i+1][j];
if(s[i]==t[j])
b=dp[i+1][j+1];
dp[i][j]=(a+b)%mod;
}
}
return dp[0][0];
}
};
// Space optimized
int mod=1e9+7;
class Solution
{
public:
int subsequenceCount(string s, string t)
{
int n=s.length();
int m=t.length();
vector<int> next(m+1,0);
next[m]=1;
for(int i=n-1;i>=0;i--)
{
vector<int> curr(m+1,0);
curr[m]=1;
for(int j=0;j<m;j++)
{
int a,b;
a=b=0;
a=next[j];
if(s[i]==t[j])
b=next[j+1];
curr[j]=(a+b)%mod;
}
next=curr;
}
return next[0];
}
};