Leetcode 120: 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
[ [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.
1 public class Solution { 2 public int MinimumTotal(IList<IList<int>> triangle) { 3 int count = triangle.Count; 4 5 if (count == 0) return 0; 6 7 var dp = new int[count + 1]; 8 9 for (int i = count - 1; i >= 0; i--) 10 { 11 for (int j = 0; j < triangle[i].Count; j++) 12 { 13 dp[j] = triangle[i][j] + Math.Min(dp[j], dp[j + 1]); 14 } 15 } 16 17 return dp[0]; 18 } 19 }