leetcode 120 Triangle

来源:互联网 发布:nginx整合php 编辑:程序博客网 时间:2024/05/16 12:44

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.

Subscribe to see which companies asked this question


class Solution {public:int minimumTotal(vector<vector<int>> &triangle) {int nrows = triangle.size();if(nrows==0) return 0;int n = triangle[nrows-1].size();//vector<vector<int>> dp(nrows, vector<int>(n,0));        vector<int> dp(n, 0);        for(int i=0; i < n; i++) {//dp[nrows-1][i] = triangle[nrows-1][i];dp[i] = triangle[nrows-1][i];}for(int i = nrows-2; i>=0; i--) {for(int j=0; j < triangle[i].size(); j++) {//dp[i][j] = min(dp[i+1][j]+triangle[i][j], dp[i+1][j+1]+triangle[i][j]);dp[j] = min(dp[j]+triangle[i][j], dp[j+1]+triangle[i][j]);}}//return dp[0][0];return dp[0];}};


/*class Solution{public:int findSum(vector<vector<int>> triangle, int row, int col, int sum) {if(row>=triangle.size()) return sum;if(col<0 || col>=triangle[row].size()) return 0;sum += triangle[row][col];int temp1 = findSum(triangle, row+1, col, sum);int temp2 = findSum(triangle, row+1, col+1, sum);return temp1 < temp2 ? temp1 : temp2;}int minimumTotal(vector<vector<int>> &triangle) {int nrows = triangle.size();if(nrows==0) return 0;return findSum(triangle, 0, 0, 0);}}*/


0 0
原创粉丝点击