Triangle - Leetcode

来源:互联网 发布:淘宝上架后过期不存在 编辑:程序博客网 时间:2024/06/10 02:34

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.

思路:要确保路径之和最小,一定要把所有的情况都走过来,同时记录所遇到的最小值。上一个结果会影响下一个结果,并不能决定下一个结果,这就是这个题目的规律。f(i,j) = min{f(i-1,j)+(i,j) , f(i-1,j-1)+(i,j)}

public class Solution {    public int minimumTotal(List<List<Integer>> triangle) {        if(triangle.size()<1)        return 0;                int[][] f = new int[triangle.size()][triangle.get(triangle.size()-1).size()]; for(int i=0; i<f.length; i++) for(int j=0; j<f[0].length; 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<1)            f[i][j] = f[i-1][j]+triangle.get(i).get(j);            else            f[i][j] = Math.min(f[i-1][j],f[i-1][j-1])+triangle.get(i).get(j);        }        Arrays.sort(f[triangle.size()-1]);        return f[triangle.size()-1][0];    }}

还有更加简洁的方法,从后往前逆运算。 待续~


0 0
原创粉丝点击