Created
June 15, 2017 07:17
-
-
Save hsinewu/5380ae77f241cb86f9b1eea6b5907e24 to your computer and use it in GitHub Desktop.
Longest Palindromic Subsequence
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def lps(i, j) | |
return $dp[i][j] if $dp[i][j] | |
return 1 if i==j | |
return 0 if i>j | |
if $a[i] == $a[j] | |
z = lps(i+1, j-1) + 2 | |
else | |
z = [ lps(i+1, j), lps(i, j-1) ].max | |
end | |
$dp[i][j] = z | |
end | |
$dp = Hash.new [] | |
$a = [1, 5, 2, 4, 3, 3, 2, 4, 5, 1] | |
p lps(0, $a.size-1) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment