LeetCode 120. Triangle

原题链接在这里:https://leetcode.com/problems/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.

题解:

从底往上动态规划. dp里的每一个元素都是从底走到这一点的最小值,转移方式是dp在下一行与自己临近的两个元素的最小值加上triangle在这点本身的元素.

dp[j] = Math.min(dp[j],dp[j+1]) + triangle.get(i).get(j).

最后返回dp[0]即可.

Time Complexity: O(n^2), n是triangle的高度, 每个点都走了一遍. Space: O(n).

AC Java:

 1 class Solution {
 2     public int minimumTotal(List<List<Integer>> triangle) {
 3         if(triangle == null || triangle.size() == 0 || triangle.get(0).size() == 0){
 4             return 0;
 5         }
 6         
 7         int m = triangle.size();
 8         int n = triangle.get(m-1).size();
 9         int [] dp = new int[n+1];
10         
11         //dp更新从triangle下到上, 取dp[j]和dp[j+1]小值加上triangle当前点的val
12         for(int i = m-1; i>=0; i--){
13             List<Integer> row = triangle.get(i);
14             for(int j = 0; j<row.size(); j++){
15                 dp[j] = Math.min(dp[j], dp[j+1]) + row.get(j);
16             }
17         }
18         
19         return dp[0];
20     }
21 }

 

posted @ 2015-09-12 03:08  Dylan_Java_NYC  阅读(233)  评论(0编辑  收藏  举报