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.
分析:该题可以用暴力搜索的方式将所有path的和存在一个vector中,但这样的空间复杂度是O(2^n)。为了使空间复杂度降到O(n),我们可以用动态规划里record的方式,这里的record我们只需记录到上一行每个位置path的最小sum,然后通过这个计算到本行每个位置path的最小sum。代码如下:
1 class Solution { 2 public: 3 int minimumTotal(vector<vector<int> > &triangle) { 4 vector<int> pre_sum, cur_sum; 5 pre_sum.push_back(triangle[0][0]); 6 cur_sum.push_back(triangle[0][0]); 7 for(int i = 1; i < triangle.size(); i++){ 8 cur_sum.clear(); 9 for(int j = 0; j < triangle[i].size(); j++){ 10 if(j == 0) cur_sum.push_back(pre_sum[0]+triangle[i][j]); 11 else if(j == triangle[i].size()-1) cur_sum.push_back(pre_sum.back()+triangle[i][j]); 12 else cur_sum.push_back(min(pre_sum[j-1]+triangle[i][j],pre_sum[j]+triangle[i][j])); 13 } 14 pre_sum = cur_sum; 15 } 16 return *min_element(cur_sum.begin(),cur_sum.end()); 17 } 18 };
不过上面的方法仍不是最好的,虽然它利用了做备忘录的方式,但没有利用动态规划的方法,这道题用动态规划的方法解,更简洁,空间复杂度仅为O(1)。本题的递推公式很简单直接,f[i][j] = min(f[i+1][j], f[i+1][j+1]) + triangle[i][j]。由于在扫过triangle[i][j]后便不再用,我们可以用triangle做备忘录的数据结构,从而将空间复杂度降为O(1)。代码如下:
class Solution { public: int minimumTotal(vector<vector<int> > &triangle) { for (int i = triangle.size() - 2; i >= 0; --i) for (int j = 0; j < i + 1; ++j) triangle[i][j] += min(triangle[i + 1][j], triangle[i + 1][j + 1]); return triangle[0][0]; } };
递归方法,但超时:
class Solution { public: int minimumTotal(vector<vector<int> > &triangle) { if(triangle.size() == 0) return 0; return getMinSum(triangle, 0, 0); } int getMinSum(vector<vector<int> > &triangle, int i, int j){ if(i == triangle.size()-1) return triangle[i][j]; return min(getMinSum(triangle, i+1, j), getMinSum(triangle, i+1, j+1)) + triangle[i][j]; } };