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).
1 class Solution { 2 public: 3 int minimumTotal(vector<vector<int> > &triangle) { 4 int size = triangle.size(); 5 vector<int> table(size, 0); 6 for (int i = 0; i < size; ++i) { 7 table[i] = triangle[size - 1][i]; 8 } 9 for (int i = size - 2; i >= 0; --i) { 10 for (int j = 0; j <= i; ++j) { 11 table[j] = min(table[j], table[j + 1]) + triangle[i][j]; 12 } 13 } 14 return table[0]; 15 } 16 };
自底向上dp. 如果允许改变三角形本身,直接利用其本身空间即可。