I am trying to solve this problem. Problem is: Given a string S and a string T, count the number of distinct subsequences of T in S.
A subsequence of a string is a new string which is formed from the original string by deleting some (can be none) of the characters without disturbing the relative positions of the remaining characters. (ie, "ACE" is a subsequence of "ABCDE" while "AEC" is not).
Here is an example: S = "rabbbit", T = "rabbit"
Answer should be 3.
class permute:
def __init__(self):
self.count = 0
def count_permute(self, s, t, i, j):
print(i, j)
if t in s:
self.count += 1
return
if i >= len(s) or j >= len(t):
return
self.count_permute(s, t, i+1, j)
if s[i] == t[j] and j == (len(t)-1):
self.count += 1
self.count_permute(s, t, i+1, j+1)
else:
self.count_permute(s, t, i+1, j+1)
def print_count(self):
print(self.count)
p = permute()
p.count_permute("rabbbit", "rabbit", 0, 0)
p.print_count()
There is also dynamic programming solution which I know by creating a matrix. However I wanted to know where I am going wrong with this recursive approach? Currently it is printing 6 but answer should be 3.