[英]Going from a top-down to a bottom-up algorithm (DP)
I have created this algorithm to compute the longest palindrome subsequence (word that is the same when mirrors, ie "aba", "racecar"), and have done so using a recursive top-down approach. 我创建了此算法来计算最长的回文序列(在镜像时相同的词,即“ aba”,“ racecar”),并使用递归自顶向下方法进行了计算。 I know that it's possible to turn these into iterative algorithms working from the bottom-up, but I am having trouble seeing how this could be accoplished
我知道有可能将它们从下往上转换为迭代算法,但是我很难看到如何实现
My code 我的密码
def palindrome(string, r = {})
return 1 if string.length == 1
return 2 if string[0] == string[1] and string.length == 2
return r[string] if r.include?(string)
n = string.length
if string[0] == string[n-1]
r[string] = palindrome(string[1..n-2],r) + 2
else
r[string] = [palindrome(string[0..n-2],r), palindrome(string[1..n-1],r)].max
end
end
When you use negative numbers when fetching an item from an array, the array counts the elements from the end , so you don't have to keep the n
variable 当您从数组中获取项目时使用负数时,该数组从末尾开始计数元素,因此您不必保留
n
变量
if string[0] == string[-1] # <= same as string[n-1] r[string] = palindrome(string[1..-2],r) + 2 # <= same as string[1..n-2]
I don't know how performant this is, but here is a top-down suggestion: 我不知道这有多好,但是这是一个自上而下的建议:
def palindrome(string) chars = string.chars chars.length.downto(1).find do |length| chars.each_cons(length).any? { |cons| cons == cons.reverse } end end
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.