leetcode120 Triangle

来源:互联网 发布:国事访问知乎 编辑:程序博客网 时间:2024/05/31 19:41

题目

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.

分析

题目的要求是找出在给出的三角形里找出一条从上到下的和最小的路径。
同别的动态规划的题目一样,只需要给出状态转移方程即可。
观察到,无论哪一条路径,最后一个元素总是最底层的某一个数,因此,可以通过构建一个结果数组result。
result[i][j] 表示每一条以triangle[i][j] 为最后一个元素的最小和路径,同时,可以给出状态转移方程如下:

result[i][j] = min(result[i - 1][j], result[i - 1][j - 1]) + triangle[i][j];        //此时i > 0 && j != 0 && j != iresult[i][0] = result[i - 1][0] + triangle[i][0];result[i][i] = result[i - 1][i - 1] + triangle[i][i];

但是这样在空间上的花费太大了,达到了O(n^2),题目的要求是O(n)的空间复杂度,观察状态转移方程,可以发现,每一个新状态只依赖上一层的状态信息,因此,可以只存储上一层的信息来完成状态转移。
定义result结果数组,result[j] 表示以当前迭代的行数的第j个数作为路径的最后元素的最小和路径。
因此,可以将状态转移方程改变如下:

result[j] = min(result[j - 1], result[j]) + triangle[i][j];     //i表示当前迭代到的行数,且此时j != 0 && j != i && i > 0result[0] = result[0] + triangle[i][0];     //j == 0result[i] = result[i - 1] + triangle[i][i];

代码:

class Solution {public:    int minimumTotal(vector<vector<int>>& triangle) {      int n = triangle.size();      if (n == 0) return 0;      vector<int> result(n, triangle[0][0]);      for (int i = 1; i < n; i++) {        result[i] = result[i - 1] + triangle[i][i];        for (int j = i - 1; j > 0; j--) {            result[j] = min(result[j - 1], result[j]) + triangle[i][j];        }        result[0] = result[0] + triangle[i][0];      }      return *min_element(result.begin(), result.end());    }};

运行结果

这里写图片描述

原创粉丝点击