Wednesday, March 20, 2013
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.
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];
}
}
Subscribe to:
Post Comments (Atom)
Manacher's Longest Palindromic Substring Algorithm
http://manacher-viz.s3-website-us-east-1.amazonaws.com/#/
-
Suppose a bus is running on a loop route. It takes 10 mins for the bus to finish the route. If a guy arrives at a bus stop at uniformly rand...
-
Question: You are playing a card game with me. Suppose I shuffle a deck of 52 cards, then I show you the card one by one to you from top t...
-
Move Objects There are N objects kept in a row. The ith object is at position x_i. You want to partition them into K groups. You want ...
No comments:
Post a Comment