Leetcode || Triangle

来源:互联网 发布:深圳pmp培训机构 知乎 编辑:程序博客网 时间:2024/06/05 05:55

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.

题目大意:

就是一条寻路的问题,下标为0的,只能跳到下一行下标为0或1的元素。下标为1的只能跳到下一行下标为1或2的元素,以此类推。

题目说的并不清楚,应该给多两个列子。

class Solution {public:    int minimumTotal(vector<vector<int> > &triangle) {        int N = triangle[triangle.size()-1].size();        int *path = new int[N];        vector<int> ivec;        ivec = triangle[triangle.size()-1];        for (int i = 0;i < N;i ++)        {            path[i] = ivec[i];        }        for (int i = N-2;i >= 0;i --)        {            ivec = triangle[i];            for (int j = 0;j < triangle[i].size();j ++)            {                path[j] = mymin(ivec[j]+path[j],ivec[j]+path[j+1]);            }        }        return path[0];    }    int mymin(int a,int b)    {        return a>b?b:a;    }};


0 0
原创粉丝点击