I have a recursive method/function written in C# that get the max sum path of a 2d array with over 90 rows. At about 25 rows the recursion stops. 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.

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.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top