@laofang
2016-07-17T06:42:19.000000Z
字数 1237
阅读 913
leetcode
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
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.Subscribe to see which companies asked this question
dp[i][j] 表示道[i][j]点的路径的和初始化:
状态转移:
if (j == 0)//在最左边dp[i][j] = dp[i - 1][j] + triangle[i][j];else if (j == triangle[i].Count - 1)//在最右边dp[i][j] = dp[i - 1][j - 1] + triangle[i][j];else//在中间dp[i][j] = Math.Min(dp[i - 1][j -1 ], dp[i - 1][j]) + triangle[i][j];
最后一行dp的最小值
public class Solution{public int MinimumTotal(IList<IList<int>> triangle){if (triangle.Count == 0) return 0;int[][] dp = new int[triangle.Count][];for(int i=0; i<triangle.Count; i++){dp[i] = new int[triangle[i].Count];for (int j = 0; j < triangle[i].Count; j ++){if (i > 0){if (j == 0)dp[i][j] = dp[i - 1][j] + triangle[i][j];else if (j == triangle[i].Count - 1)dp[i][j] = dp[i - 1][j - 1] + triangle[i][j];elsedp[i][j] = Math.Min(dp[i - 1][j -1 ], dp[i - 1][j]) + triangle[i][j];}else { dp[i][j] = triangle[i][j]; }}}return dp[triangle.Count - 1].Min();}}