LeetCode:120トライアングル三角形の最短経路

试题:
三角形を考えると、上から下への最小パスの合計を見つけます。各ステップは、あなたは下の行に隣接する数字に移動してもよいです。

例えば、以下の三角形が与えられ

[
     [2],
    [3,4],
   [6,5,7],
  [4,1,8,3]
]

上から下への最小経路和は11である(すなわち、2 + 3 + 5 + 1 = 11)。

注意:

ボーナスポイントあなたはここで、n三角形内の行の総数である、唯一のO(n)の余分なスペースを使用してこれを行うことができるかどうか。
代码:

import java.util.*;

class Solution {
    public int minimumTotal(List<List<Integer>> triangle) {
        if(triangle == null || triangle.size() == 0 || triangle.get(0) == null || triangle.get(0).size() == 0) return 0;
        int maxl = triangle.get(triangle.size()-1).size();
        int[][] dp = new int[2][maxl];
        int flag = 1;
        Arrays.fill(dp[0], Integer.MAX_VALUE);
        Arrays.fill(dp[1], Integer.MAX_VALUE);
        dp[0][0] = triangle.get(0).get(0);
        
        for(int i = 1; i < triangle.size(); i++){
            List<Integer> temp = triangle.get(i);
            for(int j = 0; j < temp.size(); j++){
                if(j == 0){
                    dp[flag][j] = dp[1-flag][j] + temp.get(j);
                }else if(j == temp.size()-1){
                    dp[flag][j] = dp[1-flag][j-1] + temp.get(j);
                }else{
                    dp[flag][j] = Math.min(dp[1-flag][j], dp[1-flag][j-1]) + temp.get(j);
                }
            }
            flag = 1 - flag;
        }
        int min = Integer.MAX_VALUE;
        for(int num : dp[1 - flag]){
            min = Math.min(min, num);
        }
        return min;
    }
}
公開された557元の記事 ウォンの賞賛500 ビュー153万+

おすすめ

転載: blog.csdn.net/qq_16234613/article/details/100118839