[LeetCode][Java]Triangle@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 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.

Runtime: 444 ms

动态规划思想: 从上到下一行一行的扫描并加入总体,dp[i]记录每扫描完一行,并途过本行i元素的最短路径,故dp[]记录到目前为止所有路径的长度。O(n) space

public class Solution {

public int minimumTotal(ArrayList<ArrayList<Integer>> triangle) {

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

if(triangle.size()==0) return 0;

if(triangle.size()==1) return triangle.get(0).get(0);

dp[0]=triangle.get(0).get(0);

for(int i=1;i<triangle.size();i++){

for(int j=i;j>=0;j--){

if(j==0) dp[0]+=triangle.get(i).get(0);

else if(j<i) dp[j]=triangle.get(i).get(j)+ Math.min(dp[j],dp[j-1]);

else dp[j]=dp[j-1]+triangle.get(i).get(j);

}

}

int ret=Integer.MAX_VALUE;

for(int i=0;i<dp.length;i++){

if(dp[i]<ret) ret=dp[i];

}

return ret;

}

}

上一篇:【leetcode】Triangle (#120)


下一篇:[CLR via C#]4. 类型基础及类型、对象、栈和堆运行时的相互联系