码迷,mamicode.com
首页 > 其他好文 > 详细

Triangle

时间:2014-08-14 23:26:46      阅读:219      评论:0      收藏:0      [点我收藏+]

标签:style   blog   color   使用   io   strong   for   ar   

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.

思路:依次对每一层进行求解,使用数组记录当前层和上一层的结果。对于triangle[i][j],其上层节点为triangle[i-1][j]和triangle[i-1][j+1]。

 1 class Solution {
 2 public:
 3     int minimumTotal( vector<vector<int>> &triangle ) {
 4         if( triangle.empty() ) { return 0; }
 5         vector<vector<int>> totals( 2, vector<int>( triangle.size(), 0 ) );
 6         totals[0][0] = triangle[0][0];
 7         for( int i = 1; i < (int)triangle.size(); ++i ) {
 8             vector<int> &prev = totals[(i-1)%2], &curr = totals[i%2];
 9             curr[0] = triangle[i][0] + prev[0];
10             curr[i] = triangle[i][i] + prev[i-1];
11             for( int k = 1; k < i; ++k ) {
12                 curr[k] = triangle[i][k] + min( prev[k-1], prev[k] );
13             }
14         }
15         vector<int> &curr = totals[((int)triangle.size()-1)%2];
16         int minTotal = curr[0];
17         for( size_t i = 1; i != curr.size(); ++i ) {
18             if( minTotal > curr[i] ) { minTotal = curr[i]; }
19         }
20         return minTotal;
21     }
22 };

上述方法采用的是自顶向下的求解策略,若采用自底向上的策略,我们可以获得更加简洁的代码:

 1 class Solution {
 2 public:
 3     int minimumTotal( vector<vector<int>> &triangle ) {
 4         if( triangle.empty() ) { return 0; }
 5         vector<int> sum = triangle.back();
 6         for( size_t i = triangle.size()-1; i != 0; --i ) {
 7             for( size_t k = 0; k != i; ++k ) {
 8                 sum[k] = triangle[i-1][k] + min( sum[k], sum[k+1] );
 9             }
10         }
11         return sum[0];
12     }
13 };

 

Triangle,布布扣,bubuko.com

Triangle

标签:style   blog   color   使用   io   strong   for   ar   

原文地址:http://www.cnblogs.com/moderate-fish/p/3913423.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!