Suppose n is the number of list, then the runtime is O(n^2/2), space is O(n)

We create an integer array of size n, which is also the number of digits in the last list. If list collection is empty, return 0; Then we look through each list in the collection. For the first list, only one element, set sum[0] = the value of the element. Otherwise, we can update the sum array according to the current value of element. For an element (except the first one and the last one) of index 1, we use prevSum to store the sum[j] in the previous level, ie, i -1.  we know sum[j] depends on sum[j-1] and sum[j], we choose the smaller one to add the value of current element, let prevSum points to sum[j] and update sum[j] to the sum value we get. We we get to the last list, we can use a variable to get the minimum sum.

Code:

public class Solution {
    public int minimumTotal(List<List<Integer>> triangle) {
        int n = triangle.size();
        if(n == 0) return 0;
        int[] sum = new int[n];
        int minSum = 0;
        for(int i = 0; i < n; i++){
            List<Integer> row = triangle.get(i);
            int prevSum = sum[0];
            for(int j = 0; j < row.size(); j++){
                if(i == 0) {
                    sum[0] = row.get(0); 
                    if(n == 1) return sum[0];
                }
                else{
                    if(j == 0) {
                        sum[0] = prevSum + row.get(j);
                        if(i == n-1) minSum = sum[0];
                    }
                    else if(j == row.size()-1) {
                        int cur = row.get(j);
                       sum[j] = prevSum + cur;
                       if(i == n-1) minSum = sum[j] < minSum ? sum[j] : minSum;
                    }
                    else{
                        int cur = row.get(j);
                        int leftSum = prevSum + cur;
                        int rightSum = sum[j] + cur;
                        prevSum = sum[j];
                        sum[j] = leftSum < rightSum ? leftSum : rightSum;
                        if(i == n-1) minSum = sum[j] < minSum ? sum[j] : minSum;
                    }
                }
            }
        }
        return minSum;
    }
}

 

posted on 2016-01-31 12:39  爱推理的骑士  阅读(156)  评论(0编辑  收藏  举报