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).


class Solution {

public:

  int minimumTotal(vector > &triangle) {

        int n = triangle.size();


        //动态规划

        for(int i=1; i

            for(int j=0; j

                if(j==0){

                    triangle[i][j] += triangle[i-1][j];

                }else if(j == triangle[i].size()-1){

                    triangle[i][j] += triangle[i-1][j-1];

                }else{

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

                }

            }

        }

        int res;

        if(n>0) res = triangle[n-1][0];

        for(int k=0; k

            res = min(res, triangle[n-1][k]);

        }

        return res;

  }

};

你可能感兴趣的:(LeetCode—120. Triangle)