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

LeetCode Triangle

时间:2014-11-09 13:54:18      阅读:155      评论:0      收藏:0      [点我收藏+]

标签:style   blog   io   color   sp   for   div   on   log   

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

 

 1 public class Solution {
 2     public int minimumTotal(List<List<Integer>> triangle) {
 3         int[] lastsum=new int[triangle.size()+1];
 4         int[] thissum=new int[triangle.size()+1];
 5         int sum=Integer.MAX_VALUE;
 6         if (triangle.isEmpty()) return 0;
 7         for (int i = 0; i < lastsum.length; i++) {
 8             lastsum[i]=sum;
 9             thissum[i]=sum;
10         }
11         lastsum[0]=0;
12         int j;
13         for (List<Integer> list : triangle) {
14             for (int i = 0; i < list.size(); i++) {
15                 if (i==0) {
16                     j=0;
17                 }else {
18                     j=i-1;
19                 }
20                 thissum[i]=list.get(i)+Math.min(lastsum[i],lastsum[j]);
21 
22             }
23             for (int i = 0; i < lastsum.length; i++) {
24                 lastsum[i]=thissum[i];
25             }
26         }
27         for (int i : lastsum) {
28             if (i<sum) sum=i;
29         }
30         return  sum;
31     }
32 }

 

LeetCode Triangle

标签:style   blog   io   color   sp   for   div   on   log   

原文地址:http://www.cnblogs.com/birdhack/p/4084989.html

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