LeetCode 120: Triangle

来源:互联网 发布:深圳网络代运营公司 编辑:程序博客网 时间:2024/05/16 17:52

题目链接:

https://leetcode.com/problems/triangle/description/

描述

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.

输入

输入一个二维数组,输出最小和。

输出

最小和。

样例输入

[[2],[3,4],[6,5,7],[4,1,8,3]]

样例输出

11

算法思想:

动态规划。

dp[i][j]=dp[i1][j]+triangle[i][j]dp[i1][j1]+triangle[i][j]min(dp[i1][j1], dp[i1][j])+triangle[i][j]i=0j=ii>0j>0

源代码

class Solution {public:    int minimumTotal(vector<vector<int>>& triangle) {        int sz = triangle.size(), sum = 0;        vector<int> vec;        for (int i = 0; i < sz; i++)        {            for (int j = 0; j <= i; j++)            {                if (i > 0 && j > 0 && j != i)                {                    triangle[i][j] += min(triangle[i - 1][j - 1], triangle[i - 1][j]);                }                if (i > 0 && j == 0)                {                    triangle[i][j] += triangle[i - 1][j];                }                if (i > 0 && j == i)                {                    triangle[i][j] += triangle[i - 1][j - 1];                }            }        }        int ans = 9999999;        for (int i = 0; i < sz; i++)        {            if (ans > triangle[sz - 1][i])                ans = triangle[sz - 1][i];        }        return ans;    }};
原创粉丝点击