1. 程式人生 > >Triangle(動態規劃)

Triangle(動態規劃)

ret from 新的 選擇 位置 ive 一個 top 原理

題目描述

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]; } };

Triangle(動態規劃)