简体   繁体   English

动态编程递归

[英]Dynamic Programming Recursion

I have a recursive method/function written in C# that get the max sum path of a 2d array with over 90 rows. 我有一个用C#编写的递归方法/函数,该函数获取具有90行以上的2d数组的最大和路径。 At about 25 rows the recursion stops. 在大约25行时,递归停止。 I have tried to overcome the problem implementing an example made for a Fibonacci. 我试图解决为斐波那契制作的示例时遇到的问题。 The result is, still the overflow but also the result is wrong. 结果是,仍然是溢出,而且结果是错误的。 This is what I have done and I thank you all for any solution or advise. 这就是我所做的,我感谢大家的任何解决方案或建议。

EDIT: Still not working with 90 rows. 编辑:仍然不能使用90行。

static long[,] cache = new long[1000, 1000];
private long GetTotal(int row, int column, long[,] triangle, long[,] cache)
{
    if (row == 0) return triangle[row, column];

    long myValue = triangle[row, column];
    long left = myValue + GetTotal(row - 1, column, triangle, cache);
    long right = myValue + GetTotal(row - 1, column + 1, triangle, cache);

    if (cache[row, column] !=0)   
    return cache[row, column];

    cache[row, column] = Math.Max(left, right);
    return cache[row, column]; 
} 

You should NOT cache based on row only, you should cache based on both row and column. 您不应仅基于行进行缓存,而应基于行和列进行缓存。

Your code as it is now stores one value for row, instead of multiple values per row, and one for each (row,column) combination. 您的代码现在按行存储一个值,而不是每行存储多个值,而为每个(行,列)组合存储一个值。

Your 'key' for the cache should be (row,column). 缓存的“键”应为(行,列)。 It could be solved using a 2D matrix - though it might be more expansive (in terms of weight) than a Dictionary . 可以使用2D矩阵来解决它-尽管它可能比Dictionary更大(就重量而言)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM