120. Triangle

来源:互联网 发布:网络监控机安装说明书 编辑:程序博客网 时间:2024/05/17 01:10

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.


不管了,直接粗暴,转化成dp搞定


public int minimumTotal(List<List<Integer>> triangle){int size=triangle.size();int maxlen=0;for(List<Integer> l :triangle)if(l.size()>maxlen)maxlen=l.size();int[][] dp=new int[size][maxlen];for(int i=0;i<size;i++)Arrays.fill(dp[i], Integer.MAX_VALUE>>1);List<Integer> first=triangle.get(0);for(int j=0;j<first.size();j++)dp[0][j]=first.get(j);for(int i=1;i<size;i++){int cursize=triangle.get(i).size();int lastsize=triangle.get(i-1).size();for(int j=0;j<cursize;j++){int a=Integer.MAX_VALUE>>1;int b=Integer.MAX_VALUE>>1;if(j-1>=0&&j-1<lastsize)a=dp[i-1][j-1];if(j>=0&&j<lastsize)b=dp[i-1][j];dp[i][j]=Math.min(a, b)+triangle.get(i).get(j);}}int min=Integer.MAX_VALUE;for(int i=0;i<maxlen;i++)min=Math.min(min, dp[size-1][i]);return min;}


update 2016.07.21


DP数组可以开变长,最大值使用Integer.MAX_VALUE


public class Solution {    public int minimumTotal(List<List<Integer>> triangle){int size=triangle.size();int[][] dp =new int[size][];int cnt=0;for(List<Integer> l :triangle){dp[cnt]=new int[l.size()];Arrays.fill(dp[cnt++], Integer.MAX_VALUE);}List<Integer> first=triangle.get(0);for(int j=0;j<first.size();j++)dp[0][j]=first.get(j);for(int i=1;i<size;i++){int cursize=triangle.get(i).size();int lastsize=triangle.get(i-1).size();for(int j=0;j<cursize;j++){int a=Integer.MAX_VALUE;int b=Integer.MAX_VALUE;if(j-1>=0&&j-1<lastsize)a=dp[i-1][j-1];if(j>=0&&j<lastsize)b=dp[i-1][j];int minab=Math.min(a, b);dp[i][j]=(minab==Integer.MAX_VALUE?Integer.MAX_VALUE:minab+triangle.get(i).get(j));}}int min=Integer.MAX_VALUE;for(int i=0;i<triangle.get(size-1).size();i++)min=Math.min(min, dp[size-1][i]);return min;}}


0 0
原创粉丝点击