[关闭]
@laofang 2016-07-17T06:42:19.000000Z 字数 1237 阅读 913

LeetCode120-"最短路径"-C#实现

leetcode


题目: https://leetcode.com/problems/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.

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

分析

  1. if (j == 0)//在最左边
  2. dp[i][j] = dp[i - 1][j] + triangle[i][j];
  3. else if (j == triangle[i].Count - 1)//在最右边
  4. dp[i][j] = dp[i - 1][j - 1] + triangle[i][j];
  5. else//在中间
  6. dp[i][j] = Math.Min(dp[i - 1][j -1 ], dp[i - 1][j]) + triangle[i][j];

代码

  1. public class Solution
  2. {
  3. public int MinimumTotal(IList<IList<int>> triangle)
  4. {
  5. if (triangle.Count == 0) return 0;
  6. int[][] dp = new int[triangle.Count][];
  7. for(int i=0; i<triangle.Count; i++)
  8. {
  9. dp[i] = new int[triangle[i].Count];
  10. for (int j = 0; j < triangle[i].Count; j ++)
  11. {
  12. if (i > 0)
  13. {
  14. if (j == 0)
  15. dp[i][j] = dp[i - 1][j] + triangle[i][j];
  16. else if (j == triangle[i].Count - 1)
  17. dp[i][j] = dp[i - 1][j - 1] + triangle[i][j];
  18. else
  19. dp[i][j] = Math.Min(dp[i - 1][j -1 ], dp[i - 1][j]) + triangle[i][j];
  20. }
  21. else { dp[i][j] = triangle[i][j]; }
  22. }
  23. }
  24. return dp[triangle.Count - 1].Min();
  25. }
  26. }
添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注