[leetcode] 120. 三角形最小路径和

120. 三角形最小路径和

动态规划入门题

class Solution {
    public int minimumTotal(List<List<Integer>> triangle) {
        if (triangle.get(0).size() == 0) return 0;

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

        for (int i = 0; i < triangle.size(); i++) {
            for (int j = i + 1; j < triangle.size(); j++) {
                f[i][j] = Integer.MAX_VALUE;
            }
        }

        f[0][0] = triangle.get(0).get(0);
        for (int i = 1; i < triangle.size(); i++) {
            for (int j = 0; j < i + 1; j++) {
                if (j == 0) {
                    f[i][j] = f[i - 1][j] + triangle.get(i).get(j);
                } else {
                    f[i][j] = Math.min(f[i - 1][j - 1], f[i - 1][j]) + triangle.get(i).get(j);
                }
            }
        }

        int ans = Integer.MAX_VALUE;
        for (int i = 0; i < triangle.size(); i++) {
            ans = Math.min(f[triangle.size() - 1][i], ans);
        }

        return ans;
    }
}
posted @ 2018-11-06 23:22 ACBingo 阅读(...) 评论(...) 编辑 收藏