码迷,mamicode.com
首页 > 编程语言 > 详细

[Leetcode][JAVA] Triangled

时间:2015-01-07 23:20:51      阅读:267      评论:0      收藏:0      [点我收藏+]

标签:

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问题。对于某一层i,我们只要知道i-1层每个数字处的最小路径值,然后相应的选出小的那个加上第i层的对应数值,即可得到最新的最小路径值。注意最左和最右处的最小路径值只有一个来源(无法二选一)。最后得到最底层的所有最短路径值,选出最小的那个即可。

例如,对于示例中的三角,每一处的最小路径值为:

[
     [2],
    [5,6],
   [11,10,13],
  [15,11,18,16]
]

实际上,没有必要维护整个三角形(二维矩阵),而只需要维护两层的数据即可。比如如果要知道最底层的最小路径,只需要知道倒数第二层的最小路径。所以只需要两个数组即可。
代码如下:
 1     public int minimumTotal(List<List<Integer>> triangle) {
 2         int[] dp = new int[triangle.size()];
 3         int re = 0;
 4         for(int i=0;i<triangle.size();i++) {
 5             int[] temp = new int[triangle.size()];
 6             for(int j=0;j<=i;j++) {
 7                 if(j==0) {
 8                     temp[j] = dp[j]+triangle.get(i).get(j);
 9                     re = temp[j];
10                 }
11                 else if(j==i)
12                     temp[j] = dp[j-1]+triangle.get(i).get(j);
13                 else
14                     temp[j] = Math.min(dp[j],dp[j-1])+triangle.get(i).get(j);
15                 re = Math.min(re, temp[j]);
16             }
17             dp = temp;
18         }
19         
20         return re;
21     }

 

[Leetcode][JAVA] Triangled

标签:

原文地址:http://www.cnblogs.com/splash/p/4209553.html

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