leetcode之Triangle

来源:互联网 发布:猎鲸狂人软件 编辑:程序博客网 时间:2024/06/08 18:38

原题如下:

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

思路:这道题很容易想到用动态规划,但发现前一阶段的结果是依赖后一阶段的结果的,所以又感觉动态规划行不通,但其实不然,当从后往前考虑时,问题就很容易解决了,因为从下网上是一个优选的过程,很容易用动态规划法实现。

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

这道题目的难点在于,一般的动态规划都是从前往后考虑,而这道题却需要从后往前,所以不容易想到,还是要多加练习才行啊。

另外在没实现动态规划之前,我曾用深度搜索算法实现了该题,但在leetcode上提交出现内存溢出的问题,相比动态规划算法,深度搜索确实显得太笨拙了,所以就不贴代码了。

0 0
原创粉丝点击