[LintCode] 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.

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.

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

For a given point at the bottom f(i, n - 1) = triangle[i][n - 1] + Math,min(f(i - 1, n - 2),  f(i, n - 2)); 

This recursive formula provides a straightforward solution.

 

Solution 2. Top Down Dynamic Programming

 1 public class Solution {
 2     public int minimumTotal(int[][] triangle) {
 3         // write your code here
 4         if(triangle == null || triangle.length == 0){
 5             return Integer.MAX_VALUE;
 6         }
 7         int row = triangle.length;
 8         int[][] f = new int[row][];
 9         for(int i = 0; i < row; i++){
10             f[i] = new int[triangle[i].length];
11         }
12         
13         f[0][0] = triangle[0][0];
14         for(int i = 1; i < row; i++){
15             f[i][0] = f[i - 1][0] + triangle[i][0];
16             f[i][i] = f[i - 1][i - 1] + triangle[i][i];
17         }
18         
19         for(int i = 1; i < row; i++){
20             for(int j = 1; j < i; j++){
21                 f[i][j] = Math.min(f[i - 1][j], f[i - 1][j - 1]) + triangle[i][j];
22             }
23         }
24         
25         int min = Integer.MAX_VALUE;
26         for(int i = 0; i < row; i++){
27             if(f[row - 1][i] < min){
28                 min = f[row - 1][i];
29             }
30         }
31         return min;
32     }
33 }

 

 

Solution 3. Bottom Up Dynamic Programming with space optimization, 

 1 public class Solution {
 2     public int minimumTotal(int[][] triangle) {
 3         if(triangle == null || triangle.length == 0){
 4             return 0;
 5         }
 6         int n = triangle.length;
 7         int[] path = new int[n];
 8         
 9         for(int i = 0; i < n; i++){
10             path[i] = triangle[n - 1][i];
11         }
12         
13         for(int i = n - 2; i >= 0; i--){
14             for(int j = 0; j <= i; j++){
15                 path[j] = Math.min(path[j], path[j + 1]) + triangle[i][j];
16             }
17         }
18         return path[0];
19     }
20 }

 

 

Related Problems

Minimum Path Sum

posted @ 2017-11-12 11:02  Review->Improve  阅读(175)  评论(0编辑  收藏  举报