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题目,状态转移方程为f(i, j) = f(i-1, j-1) + f(i-1, j) + c(i, j). 最直接的方法是是用二维数组去存计算的结果,但是我们发现每一次的dp只用到了上一次的dp结果,因此实际使用一个一维数组就足够了,注意更新的时候从后面往前更新,因为我们需要用到之前的结果。
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.
public int minimumTotal(List<List<Integer>> triangle) { int n = triangle.size(); int[] dp = new int[n]; dp[0] = triangle.get(0).get(0); for(int i = 1; i < n; i++) { for(int j = i; j >= 0; j--) { if(j == i) dp[j] = dp[j-1] + triangle.get(i).get(j); else if(j == 0) dp[j] = dp[j] + triangle.get(i).get(j); else dp[j] = Math.min(dp[j-1], dp[j]) + triangle.get(i).get(j); } } int min = Integer.MAX_VALUE; for(int i = 0; i < n; i++) min = min > dp[i] ? dp[i] : min; return min; }
没有评论:
发表评论