Sunday, November 15, 2015

[leetcode] Triangle

Double for loop的时候 记得分清楚i 和j 已经试过 j++写成i++ 还有应该用j用了i
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
public class Solution {
    public int minimumTotal(List<List<Integer>> triangle) {
        if (triangle == null || triangle.size() == 0){
            return 0;
        }
        
        int row = triangle.size();
        int column = triangle.get(row-1).size();
        int lookup[] = new int[column];
        for (int i = 0; i < column; i++){
            lookup[i] = triangle.get(row-1).get(i);
        }
        
        for (int i = row-2; i >= 0; i--){
            for (int j = 0; j <= i; j++){
                lookup[j] = Math.min(lookup[j], lookup[j+1])+triangle.get(i).get(j);
            }
        }
        
        return lookup[0];
    }
}

No comments:

Post a Comment