[LintCode] Triangle

Posted Push your limit!

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[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

以上是关于[LintCode] Triangle的主要内容,如果未能解决你的问题,请参考以下文章

Lintcode382.Triangle Count

LintCode 数字三角形

3 - Two Pointers Algorithm

FZU1004-Number Triangle经典动归题,核心思路及代码优化

120. Triangle

关于爬楼梯的lintcode代码