Skip to content

Instantly share code, notes, and snippets.

@vikene
Last active November 28, 2018 01:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save vikene/0a0f3488b67fcf3a4d155605c86cffec to your computer and use it in GitHub Desktop.
Save vikene/0a0f3488b67fcf3a4d155605c86cffec to your computer and use it in GitHub Desktop.
Longest Common Subsequence
def lcs_dp(X,Y, m,n):
dp_arr = [[None]* (n+1) for _ in range(m+1)]
for i in range(0, m+1):
for j in range(0,n+1):
if i == 0 or j == 0:
dp_arr[i][j] = 0
elif X[i-1] == Y[j-1]:
dp_arr[i][j] = 1 + dp_arr[i-1][j-1]
else:
dp_arr[i][j] = max(dp_arr[i-1][j],dp_arr[i][j-1])
return dp_arr[m][n]
def lcs(X,Y, m, n):
if m < 0 or n < 0:
return 0
elif X[m] == Y[n]:
return 1 + lcs(X,Y, m-1,n-1)
else:
return max(lcs(X,Y,m-1,n),lcs(X,Y,m,n-1))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment