[leetcode.com]算法题目 - 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).

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.

1 class Solution {
2 public:
3     int minimumTotal(vector<vector<int> > &triangle) {
4         // Start typing your C/C++ solution below
5         // DO NOT write int main() function
6         
7     }
8 };
答题模板

思路:假设三角形共有n行,题目中看出第i行共有i个元素。从top到bottom,我们只考虑minimum path的最后一步是停在了这n个元素的哪一个上面。用数组min_sum(k)表示最后一行到达第k个元素的最小路径(min_sum总长度为n),然后找出min_sum(k)中最小的元素即可。注意一下自上而下递推min_sum时候的递推公式,代码如下:

 1 class Solution {
 2 public:
 3     int minimumTotal(vector<vector<int> > &triangle) {
 4         // Start typing your C/C++ solution below
 5         // DO NOT write int main() function
 6         
 7         
 8         int n = triangle.size();
 9         if (0 == n) return 0;
10         if (1 == n) return triangle[0][0];
11         
12         int *min_sum = new int[n];
13         for(int i=0; i<n;i++)
14             min_sum[i] = 0;
15         
16         min_sum[0]=triangle[0][0];
17         for(int i=1;i<n;i++){
18             for(int j=triangle[i].size()-1; j>=0;j--){
19                 if (0==j){
20                     min_sum[j] += triangle[i][0]; 
21                 }else if (triangle[i].size()-1==j){
22                     min_sum[j] = min_sum[j-1]+triangle[i][j];
23                 }else{
24                     min_sum[j] = min(min_sum[j-1], min_sum[j])+triangle[i][j];
25                 }
26             }
27         }
28         
29         int minTotal = min_sum[0];
30         for(int i=1;i<n;i++){
31             minTotal = min(minTotal, min_sum[i]);
32         }
33         
34         delete[] min_sum;
35         return minTotal;
36     }
37     
38     int min(int a, int b){
39         return (a>b?b:a);
40     }
41 };
Answer

注意:一开始的时候内部j那个循环是正着写,后来发现这样有个问题,就是有可能会使用已经变动的过的值去更新下一列。

posted on 2013-09-09 19:38  Horstxu  阅读(470)  评论(0编辑  收藏  举报

导航