leetcode-120. Triangle

leetcode地址
分析:
对于这道题目开始理解错误,一直不知道如何解决,后来看了代码之后恍然大悟,其实很简单,直接通过DP就可以搞定。
从最后一行开始往上走,然后就可以解决问题。

public class Solution {
  public int minimumTotal(List<List<Integer>> triangle) {
     if (triangle == null || triangle.size() == 0) {
            return 0;
        }
        int rows = triangle.size();
        int[] D = new int[rows];
        for (int i = rows - 1; i >= 0; i--) {
            for (int j = 0; j <= i; j++) {
                if (i == rows - 1) {
                    D[j] = triangle.get(i).get(j);
                } else {
                    D[j] = triangle.get(i).get(j) + Math.min(D[j], D[j + 1]);
                }
            }
        }
        return D[0];
    }
}

你可能感兴趣的:(leetcode-120. Triangle)