题目原型:
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.
基本思路:
这是一道动态规划经典题,上一层的结果对下一层有影响,所以我们令f(0)....f(n)是第n层的结果,现在我们要计算第n+1层,那么:
1)当j=0时,f(0) = f(0) + triangle.get(n).get(j);
2)当j=triangle.get(n+1).size()-1时,f(j) = f(j-1)+triangle.get(n+1).get(j);
3)其他情况,f(j) = min(f(j-1),f(j))+triangle.get(n+1).get(j);
public int minimumTotal(ArrayList<ArrayList<Integer>> triangle) { int ret = Integer.MAX_VALUE; int[] f = new int[triangle.size()]; for(int i = 0;i<triangle.size();i++) { for(int j = triangle.get(i).size()-1;j>=0;j--) { if(j==0) { f[j]+=triangle.get(i).get(j); } else if(j==triangle.get(i).size()-1) { f[j]=f[j-1]+triangle.get(i).get(j); } else { f[j] = (f[j-1]<f[j]?f[j-1]:f[j])+triangle.get(i).get(j); } } } for(int i = 0;i<triangle.size();i++) { ret = ret<f[i]?ret:f[i]; } return ret; }
原文:http://blog.csdn.net/cow__sky/article/details/21295283