1. 程式人生 > >Leetcode 120. Triangle 三角形問題(動態規劃經典) 解題報告

Leetcode 120. Triangle 三角形問題(動態規劃經典) 解題報告

1 解題報告

首先我承認我很二哈,這道題我明明已經做過了,但是剛剛不知道為什麼又去做了一遍,而且我查了下兩次的解法還有所差別(貌似是現在的版本有進步了呢)

問題就是一個三角形的陣列,求從頂部到下方的最短路徑。。

這個問題是太過經典+Easy的DP問題了,哈哈。。

不想多講,直接看吧

PS:其實這道題倒著從底部到頂部也可以

2 原題

Given a triangle, find the minimum path sum from top to bottom. Each step you may move to adjacent numbers on the row below.
For example, given
the following triangle [ [2], [3,4], [6,5,7], [4,1,8,3] ] The minimum path sum from top to bottom is 11 (i.e., 2 + 3 + 5 + 1 = 11). Note: Bonus point if you are able to do this using only O(n) extra space, where n is the total number of rows in the triangle. Subscribe to see which companies asked this question

3 今天做的版本

今天做的版本我著重寫了下注釋,而且用的方法更加省記憶體了~~

public class Solution {
    public int minimumTotal(List<List<Integer>> triangle) {
        /*
         典型的動態規劃問題
         對於層數i的第j個節點有:dp[i][j] = triangle[i][j] + min(dp[i-1][j-1],dp[i-1][j]) (注意特殊處理邊界)

         改善:只使用O(n)的弓箭,那麼就只弄一層,使用一個lastVal來代替dp[i-1][j-1]
        */
int n = triangle.size(); int dp[] = new int[n]; //第一個為0 其他為max for(int i=1;i<n;i++) dp[i] = Integer.MAX_VALUE; int lastVal,tmp; for(int i=0;i<n;i++){ lastVal = Integer.MAX_VALUE; for(int j=0;j<=i;j++){ tmp = dp[j]; dp[j] = triangle.get(i).get(j) + Math.min(dp[j],lastVal); lastVal = tmp; } } int res = Integer.MAX_VALUE; for(int i=0;i<n;i++) res = Math.min(res,dp[i]); return res; } }

4 很久前做的版本

public class Solution {
    public int minimumTotal(List<List<Integer>> triangle) {
        if(triangle.size()==0)
            return 0;
        int dp[]=new int[triangle.size()];
        int last[]=new int[triangle.size()];
        int tmp[];
        dp[0]=triangle.get(0).get(0);
        last[0]=triangle.get(0).get(0);
        for(int i=1;i<triangle.size();i++){
            List<Integer> line=triangle.get(i);
            dp[0]=line.get(0)+last[0];
            dp[i]=line.get(i)+last[i-1];
            for(int j=1;j<i;j++){
                dp[j]=Math.min(last[j],last[j-1])+line.get(j);
            }
            tmp=last;
            last=dp;
            dp=tmp;
        }
        int result=last[0];
        for(int i=1;i<triangle.size();i++){
            result=Math.min(result,last[i]);
        }
        return result;

    }
}