代码之家  ›  专栏  ›  技术社区  ›  stevenpcurtis

不使用inout进行缓存的快速动态规划

  •  0
  • stevenpcurtis  · 技术社区  · 7 年前

    我一直在完成动态编程挑战。我正试图完成以下内容,但在当前的实现中得到了错误的答案

    https://www.hackerearth.com/practice/algorithms/dynamic-programming/introduction-to-dynamic-programming-1/tutorial/

    计算列表中葡萄酒的最高价格。

    每种葡萄酒只能从葡萄酒列表的末尾或开头挑选。

    这一年从1点开始

    当我在函数外部定义缓存时(即,不作为inout参数传递,如在我的解决方案中: https://gist.github.com/stevencurtis/c265e523323be73ec823084b0707a426 )相反,我下面的解决方案给出了错误的答案(49而不是50)

    var mem = [[Int]]()
    
    func dynamicMotivation (_ wines: [Int] ) -> Int {
        mem = Array(repeating: Array(repeating: 0, count: wines.count), count: wines.count)
        return motivationD(wines, year: 1, ptr1: 0, ptr2: wines.count - 1, 0)
    }
    
    func motivationD(_ wines: [Int], year: Int, ptr1: Int, ptr2: Int, _ runningTotal: Int) -> Int {
        if (ptr1 > ptr2) {return runningTotal}
        if mem[ptr1][ptr2] != 0 {
            return mem[ptr1][ptr2]
        }
        let maxProfit = max(
            motivationD(wines, year: year + 1, ptr1: ptr1 + 1, ptr2: ptr2, runningTotal + year * wines[ptr1])
            ,
            motivationD(wines, year: year + 1, ptr1: ptr1, ptr2: ptr2 - 1, runningTotal + year * wines[ptr2])
        )
        mem[ptr1][ptr2] = maxProfit
        return maxProfit
    }
    
    dynamicMotivation([2,3,5,1,4]) // 50 is the optimal solution here
    

    在这种情况下,我如何在不使用inout参数的情况下使用memonization,更正上面的代码以给出50的答案,而不是上面写的不正确的49。

    1 回复  |  直到 6 年前
        1
  •  1
  •   vacawama    7 年前

    mem 以及它是否作为 inout . 你的问题是 runningTotal 参数我删除了该参数以匹配链接中指定的算法,现在它返回正确的结果。

    var mem = [[Int]]()
    
    func dynamicMotivation (_ wines: [Int] ) -> Int {
        mem = Array(repeating: Array(repeating: 0, count: wines.count), count: wines.count)
        return motivationD(wines, year: 1, ptr1: 0, ptr2: wines.count - 1)
    }
    
    func motivationD(_ wines: [Int], year: Int, ptr1: Int, ptr2: Int) -> Int {
        if (ptr1 > ptr2) { return 0 }
        if mem[ptr1][ptr2] != 0 {
            return mem[ptr1][ptr2]
        }
    
        let maxProfit = max(
            motivationD(wines, year: year + 1, ptr1: ptr1 + 1, ptr2: ptr2) + year * wines[ptr1]
            ,
            motivationD(wines, year: year + 1, ptr1: ptr1, ptr2: ptr2 - 1) + year * wines[ptr2]
        )
        mem[ptr1][ptr2] = maxProfit
        return maxProfit
    }
    
    dynamicMotivation([2,3,5,1,4]) // 50 is the optimal solution here
    
    50