Triangle

Q:

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]
]

A:

好不容易用类似于树遍历的方式写了一版,竟然超时,难道写错了么。

下一版用dp吧。

class Solution {
 public:
  int minimumTotal(vector<vector<int> > &triangle) {
    // Start typing your C/C++ solution below
    // DO NOT write int main() function
    int h = triangle.size();
    int cur_h = 0;
    int sum = 0;
    int min_sum = 0x7fffffff;
    stack<int> poses;
    stack<bool> right;
    int pos = 0;
    while ((cur_h < h && pos < triangle[cur_h].size()) || !poses.empty()) {
      while (cur_h < h) {
        poses.push(pos);
        right.push(false);
        sum += triangle[cur_h][pos];
        cur_h++;
      }
      min_sum = min(min_sum, sum);

      while (!right.empty() && right.top()) {
        sum -= triangle[--cur_h][poses.top()];
        poses.pop();
        right.pop();
      }
      if (!poses.empty()) {
        pos = poses.top() + 1;
        right.top() = true;
      }
    }
    return min_sum;
  }
};

dp的方式如下:

class Solution {
 public:
  int minimumTotal(vector<vector<int> > &triangle) {
    int h = triangle.size();
    int cur_h = 0;
    int result = 0x7fffffff;
    vector<int> min_sums;
    min_sums.resize(h);
    min_sums[0] = triangle[0][0];
    for (int i = 1; i < h; ++i) {
      int j = 1;
      int pre = min_sums[0];
      min_sums[0] += triangle[i][0];
      for (; j < triangle[i].size() - 1; ++j) {
        int tmp = min_sums[j];
        min_sums[j] = min(pre, min_sums[j]) + triangle[i][j];
        pre = tmp;
      } 
      min_sums[j] = triangle[i][j] + pre;
    } 
    for (int i = 0; i < h; ++i) {
      result = min(result, min_sums[i]);
    } 
    return result;
  } 
};

 

posted @ 2013-06-26 16:38  dmthinker  阅读(143)  评论(0)    收藏  举报