Triangle

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 is 11 (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)

题目难度:Medium

import java.util.*;

/**
 * Created by gzdaijie on 16/6/11
 * 动态规划, i 从 len -> 0
 * fun(k) = min(fun(k), fun(k + 1)) + matrix[i][k]
 */
public class Solution {
    public int minimumTotal(List<List<Integer>> triangle) {
        int len = triangle.size();
        int[] result = new int[len + 1];

        for (int i = len - 1; i >= 0; i--) {
            List<Integer> row = triangle.get(i);
            for (int j = 0; j <= i; j++) {
                result[j] = Math.min(result[j], result[j + 1]) + row.get(j);
            }
        }
        return result[0];
    }
}
gzdaijie            updated 2016-06-11 14:04:34

results matching ""

    No results matching ""