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/#/
-
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 ...
-
The total INCOME of one BEST Chinese doctor is much SMALLER than the TAX paid of one WORST US doctor. One Chinese do...
-
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...
No comments:
Post a Comment