Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Program to find number of unique subsequences same as target in C++
Suppose we have two lowercase strings s and t, we have to find the number of subsequences of s that are equal to t. If the answer is very large then return result by 10^9 + 7.
So, if the input is like s = "abbd" t = "bd", then the output will be 2, as there are two possible subsequences "bd".
s[1] concatenate s[3]
s[2] concatenate s[3].
To solve this, we will follow these steps −
m := 10^9 + 7
-
if size of t is same as 0, then −
return 0
-
if t is same as s, then −
return 1
-
if size of t > size of s, then −
return 0
Define an array table of size same as size of t + 1 and fill with 0
table[0] := 1
-
for initialize i := 0, when i < size of s, update (increase i by 1), do −
Define an array onsave := table
-
for initialize j := 0, when j < size of table, update (increase j by 1), do −
-
if s[i] is same as t[j], then −
table[j + 1] = (table[j + 1] mod m + onsave[j] mod m)
-
table[j + 1] = (table[j + 1] mod m + onsave[j] mod m)
Let us see the following implementation to get better understanding −
Example
#include <bits/stdc++.h>
using namespace std;
int solve(string s, string t) {
int m = 1000000007;
if (t.size() == 0)
return 0;
if (t == s)
return 1;
if (t.size() > s.size())
return 0;
vector<int> table(t.size() + 1, 0);
table[0] = 1;
for (int i = 0; i < s.size(); i++) {
vector<int> onsave = table;
for (int j = 0; j < table.size(); j++) {
if (s[i] == t[j]) {
table[j + 1] = (table[j + 1] % m + onsave[j] % m) %m;
}
}
}
return table[t.size()] % m;
}
main(){
string s = "abbd", t = "bd";
cout << (solve(s, t));
}
Input
"abbd", "bd"
Output
2