[leetcode]Triangle - dp java

动态规划的

1. 转移函数f[i][j]从top到第i排第j个元素的最小距离

2. 考虑到边界问题,状态转移方程为

int left = j-1<0?0:j-1;

int right = j>i-1?i-1:j;

f[i][j]=Math.min(f[i-1][left], f[i-1][right])+triangle.get(i).get(j);

 

public class Solution {

   public int minimumTotal(List<List<Integer>> triangle) {

        if(triangle==null || triangle.isEmpty()){

            return 0;

        }

        int maxLength = triangle.get(triangle.size()-1).size();

        int[][] f = new int[triangle.size()][maxLength];

        f[0][0]=triangle.get(0).get(0);

        for(int i=1; i<triangle.size(); i++){

            for(int j=0; j<i+1; j++){

                int left = j-1<0?0:j-1;

                int right = j>i-1?i-1:j;

                f[i][j]=Math.min(f[i-1][left], f[i-1][right])+triangle.get(i).get(j);

            }

        }

        int min = f[triangle.size()-1][0];

        for(int i=1; i<triangle.get(triangle.size()-1).size(); i++){

            if(f[triangle.size()-1][i]<min){

                min = f[triangle.size()-1][i];

            }

        }

        return min;

    }

}

 

你可能感兴趣的:(LeetCode,算法)