首页 > 代码库 > [LeetCode]120.Triangle

[LeetCode]120.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.


【分析】

这是一道动态规划的题目,求一个三角形二维数组从顶到低端的最小路径和。

我们从低端向顶端计算。设状态为 S[i][j]表示从从位置 ( i, j ) 出发,到最低端路径的最小和

状态转移方程:
S[i][j] = min(S[i+1][j] + S[i+1][j+1]) +S[i][j]

S[0][0]就是要求解的答案。

时间复杂度 O(n^2) ,空间复杂度 O(1)

【代码】

    /**------------------------------------
    *   日期:2015-02-03
    *   作者:SJF0115
    *   题目: 120.Triangle
    *   网址:https://oj.leetcode.com/problems/triangle/
    *   结果:AC
    *   来源:LeetCode
    *   博客:
    ---------------------------------------**/
    #include <iostream>
    #include <vector>
    #include <algorithm>
    using namespace std;

    class Solution {
    public:
        int minimumTotal(vector<vector<int> > &triangle) {
            int size = triangle.size();
            // down-to-top
            // 第i层
            for(int i = size - 2;i >= 0;--i){
                // 第i层的第j个元素
                for(int j = 0;j <= i;++j){
                    triangle[i][j] += min(triangle[i+1][j],triangle[i+1][j+1]);
                }//for
            }//for
            return triangle[0][0];
        }
    };

    int main(){
        Solution s;
        vector<vector<int> > triangle = {{2},{3,4},{6,5,3},{4,1,8,3}};
        int result = s.minimumTotal(triangle);
        // 输出
        cout<<result<<endl;
        return 0;
    }


技术分享

[LeetCode]120.Triangle