Triangle 解答

Question

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).

Solution 1 -- DP

We define dp[i] to be the smallest sum that must include nums[i]. For easier understanding, we maintain two lists to record dp[i] information. Time complexity O(n^2) and space cost O(n).

 1 public class Solution {
 2     public int minimumTotal(List<List<Integer>> triangle) {
 3         if (triangle == null || triangle.size() < 1)
 4             return 0;
 5         int size = triangle.size(), result = Integer.MAX_VALUE;
 6         List<Integer> currentList, currentDP, prevDP = new ArrayList<Integer>();
 7         for (int i = 0; i < size; i++) {
 8             currentList = triangle.get(i);
 9             currentDP = new ArrayList<Integer>();
10             if (i == 0) {
11                 currentDP.add(currentList.get(i));
12             } else {
13                 for (int j = 0; j <= i; j++) {
14                     int tmpMin;
15                     // Three Cases
16                     if (j == 0)
17                         tmpMin = currentList.get(j) + prevDP.get(0);
18                     else if (j == i)
19                         tmpMin = currentList.get(j) + prevDP.get(j - 1);
20                     else
21                         tmpMin = currentList.get(j) + Math.min(prevDP.get(j), prevDP.get(j - 1));
22                     currentDP.add(tmpMin);
23                 }
24             }
25             prevDP = currentDP;
26         }
27         // Select minimum number of dp[i]
28         for (int tmp : prevDP)
29             result = Math.min(tmp, result);
30         return result;
31     }
32 }

Solution 2 -- Bottom Up

In this way, we need not to consider the three cases discussed above.

 1 public class Solution {
 2     public int minimumTotal(List<List<Integer>> triangle) {
 3         if (triangle == null || triangle.size() < 1)
 4             return 0;
 5         int size = triangle.size();
 6         int[] dp = new int[size];
 7         for (int i = 0; i < triangle.get(size - 1).size(); i++)
 8             dp[i] = triangle.get(size - 1).get(i);
 9         // Iterate from last second row
10         for (int i = size - 2; i >= 0; i--) {
11             List<Integer> tmpList = triangle.get(i);
12             for (int j = 0; j < tmpList.size(); j++) {
13                 dp[j] = tmpList.get(j) + Math.min(dp[j], dp[j + 1]);
14             }
15         }
16         return dp[0];
17     }
18 }

 

posted @ 2015-09-21 03:30  树獭君  阅读(200)  评论(0编辑  收藏  举报