简体   繁体   English

从上到下到自下而上的算法(DP)

[英]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
  1. 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] 
  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.

相关问题 Ruby方法查找是从类的底部开始并向上,还是从顶部开始并向下? - Does the Ruby method lookup start from the bottom of a class and go up, or from the top and go down? 将命名配置文件样本树合并为自上而下的总和 - Coalescing a tree of named profile samples into a top-down summation 如何在Ruby中从下到上读取文件? - How to read a file from bottom to top in Ruby? 从下到上无限滚动的 rails 中的分页 - Pagination in rails with infinite scroll from bottom to top 计算并显示 ruby on rails 从下到上的余额 - Calculate and display the balances from bottom to top in ruby on rails Phusion Passenger中是否存在某种机制来防止整个应用程序崩溃? - Is there some sort of mechanism in Phusion Passenger to keep whole applications from going down? 从日志文件动态获取总启动/关闭时间 - Dynamically get the total up/down time from a log file 加快算法解决方案 - Speeding up solution to algorithm 在轨道上的 ruby 中从下到上填充或显示费用表的表行条目 - Populate or display entries from bottom to top of the table row of the expenses table in ruby on rails 查找从4x4阵列的左上角到右下角的所有可能路径 - Find all possible paths from top-left to bottom-right corner of 4x4 array
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM