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.

 1 public class Solution {
 2     public int minimumTotal(ArrayList<ArrayList<Integer>> triangle) {
 3         // Start typing your Java solution below
 4         // DO NOT write main() function
 5         if(triangle == null) return 0;
 6         if(triangle.size() == 0) return 0;
 7         int[] a = new int[triangle.size()];
 8         for(int i = 0; i < triangle.size(); i ++){
 9             a[i] = triangle.get(triangle.size() - 1).get(i);
10         }
11         for(int j = triangle.size() - 1; j > 0; j --){
12             for(int i = 0; i < j; i ++){
13                 a[i] = triangle.get(j - 1).get(i) + Math.min(a[i],a[i+1]);
14             }
15         }
16         return a[0];
17     }
18 }

第二遍:

 1 public class Solution {
 2     public int minimumTotal(ArrayList<ArrayList<Integer>> triangle) {
 3         // IMPORTANT: Please reset any member data you declared, as
 4         // the same Solution instance will be reused for each test case.
 5         Integer[] a = triangle.get(triangle.size()-1).toArray(new Integer[0]);
 6         for(int j = triangle.size() - 1; j > 0; j --)
 7             for(int i = 0; i < j; i ++)
 8                 a[i] = triangle.get(j-1).get(i) + Math.min(a[i],a[i+1]);
 9         return a[0];
10     }
11 }

 

posted on 2013-09-24 07:26  Step-BY-Step  阅读(234)  评论(0编辑  收藏  举报

导航