One. Problem Description
Given a triangle, find the minimum and the top-down path. Each step can move to the next line adjacent nodes.
For example, given triangle:
[
[2],
[3,4],
[6,5,7],
[4,1,8,3]
]
Top-down and minimum path 11 (i.e., 2 + 3 + 5 + 1 = 11).
Description:
If you can use only O (n) extra space (n number of rows as a triangle) to solve this problem, then your algorithm will be a plus.
two. Problem-solving ideas
Body of ideas: the use of bottom-up dynamic programming algorithm to solve it. Find the state transition function. N is the n-th row to the last row of the maximum value, i is a i-th row.
f (n) (i) = f (n) (i) + min (f (n + 1) (i), f (n + 1) (i + 1))
Step a: The state transition equation, we can be counted from the last line, all the values obtained on each line, and instead of the line.
Step Two: Repeat steps until the first line is replaced with the new values, the new output value is the value of the request.
three. Results of the
When execution: 7 ms, beat the 27.06% of all users in java submission
Memory consumption: 37.2 MB, defeated 77.58% of all users in java submission
four. Java code
class Solution { public int minimumTotal(List<List<Integer>> triangle) { if(triangle.size()==0) { return 0; } for(int i=triangle.size()-2;i>=0;i--) { List<Integer> list=new ArrayList<Integer>(triangle.get(i)); for(int j=0;j<list.size();j++) { int temp=list.get(j)+Math.min(triangle.get(i+1).get(j), triangle.get(i+1).get(j+1)); list.set(j, temp); } triangle.set(i, list); } return triangle.get(0).get(0); } }