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.

大致题意

在三角形中找到一条从顶部到底部的最短路径

题解

问题类型:动态规划

最优子结构:用dpi表示当前迭代第i层的时候到达第j个元素的最短路径

状态转移方程:

dp[i][j]=min(dp[i - 1][j - 1] + triangle[i][j], dp[i - 1][j] + triangle[i][j]);

最后输出最后一行最小的,结束

代码如下(用了状态压缩)

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

sugerPocket
1 声望0 粉丝