簡體   English   中英

簡單的 java 遞歸,有人可以幫我理解堆棧 memory 中發生的邏輯嗎?

[英]Simple java recursion, Can someone help me understand the logic going on in the stack memory?

我正在對 udemy 上的 DS + 算法進行一些自學,但我很難掌握遞歸。 我已經發布了一個方法,該方法將采用數組和索引並返回遵循所選元素不能垂直的規則可以實現的最大總和。

在示例 arr = {6, 7, 1, 30, 8, 2, 4} 中,答案是 7, 30, 4 = 41。我添加了一些打印來幫助我理解發生了什么,但之后我迷路了第一個 math.max() 返回

public class House_Thieft_DC {

    public int maxMoney(int[] HouseNetWorth) {
        return maxMoneyRecursive(HouseNetWorth, 0);
    }//end of method

    private int maxMoneyRecursive(int[] HouseNetWorth, int currentIndex) {
        if (currentIndex >= HouseNetWorth.length) 
            return 0;

        System.out.println("HouseNetWorth: "+HouseNetWorth[currentIndex]);
        
        int stealCurrentHouse = HouseNetWorth[currentIndex] + maxMoneyRecursive(HouseNetWorth, currentIndex + 2);
        int skipCurrentHouse = maxMoneyRecursive(HouseNetWorth, currentIndex + 1);
        
        System.out.print("stealCurrentHouse: "+stealCurrentHouse);      
        System.out.print("    skipCurrentHouse: "+skipCurrentHouse);
        System.out.println("    max: "+Math.max(stealCurrentHouse, skipCurrentHouse)+"\n");

        return Math.max(stealCurrentHouse, skipCurrentHouse);
    }//end of method

    public static void main(String[] args) {
        House_Thieft_DC ht = new House_Thieft_DC();
        int[] HouseNetWorth = {6, 7, 1, 30, 8, 2, 4}; //ans is 7, 30, 4 = 41
        System.out.println(ht.maxMoney(HouseNetWorth));
        //HouseNetWorth = new int[] {20, 5, 1, 13, 6, 11, 40};
        //System.out.println(ht.maxMoney(HouseNetWorth));
    }
}// end of class

由於每個調用都基於更右側的項目,因此有助於從右到左計算maxMoneyRecursive的結果

6、7、1、30、8、2、4

應該

41, 41, 34, 34, 12, 4, 4

為了更好地理解和記錄計算流程,為調用循環添加一個參數可能會有所幫助,例如

private int maxMoneyRecursive(int[] HouseNetWorth, int currentIndex, int callingIndex)

如果您總是用currentIndex填充callingIndex ,您將看到每個計算的來源。

暫無
暫無

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

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