LeetCode每日一题:三角形

问题描述

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 is11(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.

问题分析

这道题让我们找从顶到底的最短路径,每次只能到下一行相连的两个数。可以使用O(n)的辅助空间。一道典型的动态规划题目。
设distance[i][j]表示到达第i行第j列数的最短路径,那么状态转移方程可以写为:

distance[i][j]=
distance[i][j]+min(distance[i+1][j],distance[i+1][j+1])

这里使用ArrayList代替了数组,处理起来有点小麻烦

代码实现

public int minimumTotal(ArrayList> triangle) {
        if (triangle.size() == 0) return 0;
        ArrayList> distance = new ArrayList>(triangle);
        for (int i = distance.size() - 2; i >= 0; i--) {
            for (int j = 0; j <= i; j++) {
                distance.get(i).set(j, distance.get(i).get(j) +
                        Math.min(distance.get(i + 1).get(j), distance.get(i + 1).get(j + 1)));
            }

        }
        return distance.get(0).get(0);
    }

你可能感兴趣的:(LeetCode每日一题:三角形)