Leetcode 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.

 

非常经典的动态规划题

看到题目有点像树的结构,可以考虑用深搜(DFS)去做,但每个结点总是共享一个子节点,有重叠子问题

如果从x和y到达最底部结点的最短路径知道,则在选择x和y结点时一定会选择min(pathx ,pathy)最小的结点走,具有最优子结构特性

故可以考虑利用动态规划解决(DP)

设决策变量为path[i][j],表示第i层的第j个结点到最底层的最短路径

则path[i][j] = min(path[i+1][j],path[i+1][j+1]) + triangle[i][j] ,可以考虑滚动数组的做法,由于底层的数据不会用到

利用新计算的值覆盖原有的值,故只需要考虑一维数组

path[j] = min(path[j] , path[j+1]) + triangle[i][j]; (j代表每层的第几个结点)

注意计算时要从前往后计算,不然会改变原有的值,做完这题可以看一下从后往前计算的题Pascal's Triangle II

int minimumTotal(vector<vector<int> > &triangle) {
    int n = triangle.size();
    vector<int> path(triangle[n-1].begin(),triangle[n-1].end());
    for(int i = n-2; i>= 0; -- i){
        for(int j = 0 ; j < triangle[i].size(); ++ j){
            path[j] = min(path[j],path[j+1]) + triangle[i][j];
        }
    }
    return path[0];
} 

 

posted @ 2014-06-22 21:35  OpenSoucre  阅读(296)  评论(0编辑  收藏  举报