[Leetcode] 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).

 

在输入的数组中直接修改,这样就不需要额外的空间了,不知道这样符合题目的本意不,不过已AC。

 1 class Solution {
 2 public:
 3     int minimumTotal(vector<vector<int> > &triangle) {
 4         if (triangle.size() == 1) {
 5             return triangle[0][0];
 6         }
 7         int min_sum = INT_MAX;
 8         for (int i = 1; i < triangle.size(); ++i) {
 9             for (int j = 0; j <= i; ++j) {
10                 if (j == 0) {
11                     triangle[i][j] += triangle[i-1][j];
12                 } else if (j == i) {
13                     triangle[i][j] += triangle[i-1][j-1];
14                 } else {
15                     triangle[i][j] += min(triangle[i-1][j-1], triangle[i-1][j]);
16                 }
17                 if (i == triangle.size() - 1) {
18                     min_sum = min(min_sum, triangle[i][j]);
19                 }
20             }
21         }
22         return min_sum;
23     }
24 };

 

posted @ 2014-04-01 00:04  Eason Liu  阅读(238)  评论(0编辑  收藏  举报