Iam trying to print all possible longest common subsequence using below code
1-Firstly i found LCS length dp matrix and trying using recursion to produce all possible outputs.
################################################Print ALL LCS ################################333
class Solution:
def LcsHelper(self,text1,text2,dp,output,m,n):
if m<0 or n<0:
return output
if text1[m]==text2[n]:
out=[]
for elem in output.copy():
out.append(text1[m]+elem)
#output.remove(elem) # Remove this line show every possiblities
return self.LcsHelper(text1,text2,dp,out,m-1,n-1)
elif dp[m-1][n]>dp[m][n-1]:
return self.LcsHelper(text1,text2,dp,output,m-1,n)
elif dp[m-1][n]<dp[m][n-1]:
return self.LcsHelper(text1,text2,dp,output,m,n-1)
else:
out1=self.LcsHelper(text1,text2,dp,output,m-1,n)
out2=self.LcsHelper(text1,text2,dp,output,m,n-1)
return out1+out2
def printlongestCommonSubsequence(self, text1,text2):
m, n = len(text1), len(text2)
dp = [[0]*(n+1) for _ in range(m+1)]
for i in range(1, m+1):
for j in range(1, n+1):
if text1[i-1] == text2[j-1]:
dp[i][j] = dp[i-1][j-1]+1
else:
dp[i][j] = max(dp[i][j-1], dp[i-1][j])
return self.LcsHelper(text1,text2,dp,[""],m-1,n-1)
Input and output
s=Solution()
text1="BDCABA"
text2="ABCBDAB"
s.printlongestCommonSubsequence(text1,text2)
-----output--------------
['BDAB',
'AB',
'BAB',
'AB',
'BCAB',
'CAB',
'A',
'BA',
'A',
'BCA',
'CA',
'BCA',
'CA',
'BCBA',
'CBA']
Current, Iam getting every possibilities along with some dummy possibilities. actually every time i add the character to the output list, i need to popout the character and insert to it as old append with new. But when i add the line
output.remove(elem)
It then only show one possibility of LCS, not all. Please help, where iam going wrong?
['BDAB']