首页 > 学院 > 开发设计 > 正文

LeetCode:triangle

2019-11-08 02:46:20
字体:
来源:转载
供稿:网友

链接:https://www.nowcoder.com/PRactice/2b7995aa4f7949d99674d975489cb7da?tpId=46&tqId=29060&tPage=1&rp=1&ru=/ta/leetcode&qru=/ta/leetcode/question-ranking 来源:牛客网

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.

class Solution {public: int minimumTotal(vector<vector<int> > &triangle) { for(int i=triangle.size()-2;i>=0;--i) { for(int j=0;j<i+1;++j) { triangle[i][j] = min(triangle[i+1][j],triangle[i+1][j+1])+triangle[i][j]; } } return triangle[0][0]; }};
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表