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 is11(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.
 
 
题意:
  给定一个数字三角形,找到从顶部到底部的最小路径和。每一步可以移动到下面一行的相邻数字上。
 

解题思路:

  • 矩阵型DP问题
  • 自顶而下或者自底而上
  • 采用一个向量dp,复制。三角形最后一行,作为用来更新的一位数组。然后逐个遍历这个dp数组,对于每个数字,和它之后的元素比较选择较小的再加上上面一行相邻位置的元素做为新的元素,然后一层一层的向上扫描,整个过程和冒泡排序的原理差不多,最后最小的元素都冒到前面,第一个元素即为所求。

代码实现:

class Solution {
public:
    int minimumTotal(vector<vector<int> > &triangle) {
        int n=triangle.size();
        vector<int>dp(triangle.back());
        for(int i=n-2;i>=0;i--){
            for(int j=0;j<=i;j++){
                dp[j]=min(dp[j+1],dp[j])+triangle[i][j];
            }
        }
        return dp[0];
    }
};

 

 
posted @ 2017-11-12 16:15  涛声依旧~  阅读(329)  评论(0编辑  收藏  举报