Wednesday, March 20, 2013


Given a triangle, find the minimum path sum from top to bottom. Each step you may move to adjacent numbers on the row below.

Using DP, calculate the minimal path sum from bottom to top.
Using an array to restore the partial result.

public class Solution {
    public int minimumTotal(ArrayList<ArrayList<Integer>> triangle) {
        // Start typing your Java solution below
        // DO NOT write main() function
        int height = triangle.size()-1;
        int[] ret = new int[height + 1];
        for(int i = 0; i<triangle.get(height).size(); i++){
            ret[i] = triangle.get(height).get(i);
        while(--height >=0){
            for(int i = 0; i<triangle.get(height).size();i++){
                int val = triangle.get(height).get(i);
                val += Math.min(ret[i],ret[i+1]);
                ret[i] = val;
        return ret[0];

No comments:

Post a Comment

Manacher's Longest Palindromic Substring Algorithm