Leetcode Triangle

来源:互联网 发布:批判性思维工具 知乎 编辑:程序博客网 时间:2024/05/17 04:52

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.


Difficulty: Medium


public class Solution {    public int minimumTotal(List<List<Integer>> triangle) {        int len = triangle.size();        for(int i = 1; i < len; i++){            for(int j = 0; j < triangle.get(i).size(); j++){                if(j == 0){                    triangle.get(i).set(j, triangle.get(i).get(j) + triangle.get(i - 1).get(j));                }                else if(j == triangle.get(i).size() - 1){                    triangle.get(i).set(j, triangle.get(i).get(j) + triangle.get(i - 1).get(j - 1));                }                else{                    triangle.get(i).set(j, Math.min(triangle.get(i).get(j) + triangle.get(i - 1).get(j), triangle.get(i).get(j) + triangle.get(i - 1).get(j - 1)));                }            }        }        int ans = Integer.MAX_VALUE;        for(int i = 0; i < triangle.get(len - 1).size(); i++){            ans = Math.min(ans, triangle.get(len - 1).get(i));        }        return ans;    }}


0 0