簡體   English   中英

使用巨大的二維數組獲取最大路徑和遞歸

[英]Get Max Path Sum Recursive with huge 2d 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) - 這是一個相當大的數字。

考慮將您的代碼轉換為動態編程解決方案,這基本上是實現此類遞歸的有效方法,而無需兩次計算某些值(您的代碼就是這種情況)。

最簡單的方法是自頂向下的動態規划,也稱為“記憶”
只需添加一個字典,我們稱之為cache ,並在函數的開頭 - 檢查 (row,column) 是否在緩存中。 如果是 - 只需返回已經計算的值。
否則 - 計算值,並在返回之前 - 將其存儲在cache

這是基於您的代碼的代碼。 它不會編譯 - 但它應該展示手頭的問題。

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;
} 

嗨,阿米特,這是我所做的,但現在實際上更糟。 現在溢出發生在 25 行,而在編輯之前發生在 40 行。

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

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

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

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM