c# - 使用巨大的二维数组递归获取最大路径和

标签 c# algorithm multidimensional-array

我必须获得二维数组的最大路径和。
我可以设法获取最多 40 行,但函数之后不返回任何值。
有人能帮我吗?

private int GetTotal(int row, int column, int[,] triangle)
{
    if (row == 0) return triangle[row, column];

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

    return Math.Max(left, right);
} 

最佳答案

您正在观察算法的指数运行时间。该算法的运行时间为 O(2^rows) - 这是一个相当大的数字。

考虑将您的代码转换为 Dynamic Programming解决方案,这基本上是实现此类递归的有效方法,无需两次计算某些值(代码中就是这种情况)。

最简单的方法是自上而下的动态规划,也称为 "memorization"
只需添加一个字典,我们称之为缓存,并在函数的开头 - 检查(行,列)是否在缓存中。如果是 - 只需返回已经计算出的值。
否则 - 计算值,并在返回之前 - 将其存储在缓存中。

这是基于您的代码的伪代码。它不会编译 - 但它应该演示当前的问题。

private long GetTotal(int row, int column, Pyramid pyramid, Dictionary<Pair<int,int>,long> cache)
{
    if (row == 0) return pyramid[row, column];
    //add a check if you already calculated for this row and column:
    Pair<int,int> p = new Pair<int,int>(row,column);
    if cache.ContainsKey(p) return cache.Get(p);

    int myValue = pyramid[row, column];
    long left = myValue + GetTotal(row - 1, column, pyramid, cache); //sending the dictionary as well...
    long right = myValue + GetTotal(row - 1, column + 1, pyramid, cache);

    long best = Math.Max(left, right);
    //before returning: store the just calculated value in the cache:
    cache.Add(p,best);
    return best;
} 

关于c# - 使用巨大的二维数组递归获取最大路径和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22936810/

相关文章:

C# 将泛型函数作为参数传递

c# - 如何使用 XAML 在默认浏览器中打开 URL(windows-8 应用程序)

algorithm - 查找满足一个条件的所有组

java - 无法在Java中初始化二维数组

php - 如何找到潮汐数据的所有波峰和波谷?

javascript - 从javascript中的多维数组中获取所有变体

c# - 网络性能问题

c# - GridViewColumn标题内容不占据所有空间

image - 比较 2 个一位图像的相似性

performance - 具有数百万位模数和指数的模幂运算的极快方法