码迷,mamicode.com
首页 > 其他好文 > 详细

[LintCode] Triangle

时间:2017-11-12 12:22:13      阅读:128      评论:0      收藏:0      [点我收藏+]

标签:tco   rom   tom   span   des   inf   path   write   nbsp   

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

标签:tco   rom   tom   span   des   inf   path   write   nbsp   

原文地址:http://www.cnblogs.com/lz87/p/7498460.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!