标签:
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).
State: f[i][j] 表示跳到第(i,j)的位置的最小路径和。
Function:f[i][j] = min (f[i - 1][j - 1], f[i - 1][j]) (j != 0, j != i)
Initializtion: f[i][0] = f[i - 1][0] + a[i][0] f[i][i] = f[ i - 1][i - 1] + a[i][i]
Answer: min(最后一行的值)
1 public class Solution { 2 public int minimumTotal(List<List<Integer>> triangle) { 3 if (triangle == null || triangle.size() == 0) { 4 return 0; 5 } 6 7 int m = triangle.size(); 8 int[][] f = new int[m][m]; 9 f[0][0] = triangle.get(0).get(0); 10 for (int i = 1; i < m; i++) { 11 f[i][0] = f[i - 1][0] + triangle.get(i).get(0); 12 f[i][i] = f[i - 1][i - 1] + triangle.get(i).get(i); 13 } 14 15 for (int i = 1; i < m; i++) { 16 for (int j = 1; j < i; j++) { 17 f[i][j] = Math.min(f[i - 1][j], f[i - 1][j - 1]) + triangle.get(i).get(j); 18 } 19 } 20 int min = Integer.MAX_VALUE; 21 for (int i = 0; i < m; i++) { 22 min = Math.min(min, f[m - 1][i]); 23 } 24 return min; 25 } 26 }
标签:
原文地址:http://www.cnblogs.com/FLAGyuri/p/5403183.html