LeetCode OJ - Triangle

来源:互联网 发布:照片冲印软件 编辑:程序博客网 时间:2024/05/21 17:08

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.

分析:DFS估计就会超时、根据Node采用record[n]来记录每到一层,某个位置的最小路径。

class Solution {    int ret = INT_MAX;public:    int minimumTotal(vector<vector<int> > &triangle) {        if(triangle.size() == 0) return 0;        DFS(triangle, 0, 0, 0);        return ret;    }        void DFS(vector<vector<int> > &triangle, int level, int i, int item) {        item += triangle[level][i];        if(level == triangle.size() - 1) {            ret = min(ret, item);            return ;        }                DFS(triangle, level + 1, i, item);        DFS(triangle, level + 1, i + 1, item);    }};
从底至上来不断获取最大值,还是用record[n]来记录,时间复杂度为O(n^2)

class Solution {    int ret = INT_MAX;public:    int minimumTotal(vector<vector<int> > &triangle) {        int len = triangle.size();        if(len == 0) return 0;                int *record = new int[len];        for(int i = 0; i < len; i++) {            record[i] = triangle[len-1][i];        }                for(int i = len - 2; i >= 0; i--) {            for(int j = 0; j < triangle[i].size(); j++) {                int cur = triangle[i][j];                int left = cur + record[j];                int right = cur + record[j+1];                record[j] = min(left, right);            }        }        return record[0];    }};


0 0
原创粉丝点击