LeetCode Triangle

class Solution {
public:
    int minimumTotal(vector<vector<int> > &triangle) {
        if (!triangle.size() || !triangle[0].size()) return 0;
        
        int rows = triangle.size();
        int *ra = new int[rows];
        int *rb = new int[rows];
        int *tmp= NULL;
        int L, R;
        
        ra[0] = triangle[0][0];
        for (int i=1; i<rows; i++) {
            vector<int>& row = triangle[i];
            for (int j=0; j<=i; j++) {
                L = (j - 1) >= 0 ? ra[j-1] : INT_MAX;
                R = (j != i) ? ra[j] : INT_MAX;
                rb[j] = ((L < R) ? L : R) + row[j];
            }
            tmp = ra, ra = rb, rb = tmp;
        }
        
        int sum = INT_MAX;
        for (int i=0; i<rows; i++) {
            if (ra[i] < sum) sum = ra[i];
        }
        
        delete[] ra;
        delete[] rb;
        return sum;   
    }
};

这里使用了两个数组,如果入参允许改变的话可以直接在其上进行修改而不用其他额外空间,提交了一下也是可以。

第二轮:

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.

看来智商又下降了不少,只写出个dfs的先:

 1 // 17:52
 2 class Solution {
 3 private:
 4     vector<vector<int> > memo;
 5 public:
 6     int minimumTotal(vector<vector<int> > &triangle) {
 7         int len = triangle.size();
 8         memo = vector<vector<int> > (len, vector<int>(len, INT_MAX));
 9         return dfs(triangle, 0, 0);
10     }
11     
12     int dfs(vector<vector<int> >& m, int level, int idx) {
13         if (level >= m.size()) {
14             return 0;
15         }
16         if (memo[level][idx] != INT_MAX) {
17             return memo[level][idx];
18         }
19         int s1 = dfs(m, level + 1, idx);
20         int s2 = dfs(m, level + 1, idx + 1);
21         
22         return memo[level][idx] = (m[level][idx] + min(s1, s2));
23     }
24 };

 瞬间感觉自己智商又提高了:

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

 

posted @ 2014-03-21 02:06  卖程序的小歪  阅读(126)  评论(0编辑  收藏  举报