28. Triangle && Pascal's Triangle && Pascal's Triangle II

时间:2023-01-08 23:36:13

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.

思想: 经典的动态规划题。

class Solution {
public:
    int minimumTotal(vector<vector<int> > &triangle) {
        vector<int> pSum(triangle.size()+1, 0);
        for(int i = triangle.size()-1; i >= 0; --i)
            for(int j = 0; j < triangle[i].size(); ++j) 
                pSum[j] = min(pSum[j]+triangle[i][j], pSum[j+1]+triangle[i][j]);
        return pSum[0];
    }
};

 

Pascal's Triangle

Given numRows, generate the first numRows of Pascal's triangle.

For example, given numRows = 5, Return

[
     [1],
    [1,1],
   [1,2,1],
  [1,3,3,1],
 [1,4,6,4,1]
]
思想: 简单的动态规划。
class Solution {
public:
    vector<vector<int> > generate(int numRows) {
        vector<vector<int> > vec;
        if(numRows <= 0) return vec;
        
        vec.push_back(vector<int>(1, 1));
        if(numRows == 1) return vec;
        
        vec.push_back(vector<int>(2, 1));
        if(numRows == 2) return vec;
        
        for(int row = 2; row < numRows; ++row) {
            vector<int> vec2(row+1, 1);
            for(int Id = 1; Id < row; ++Id)
                vec2[Id] = vec[row-1][Id-1] + vec[row-1][Id];
            vec.push_back(vec2);
        }
        return vec;
    }
};

 

Pascal's Triangle II

Given an index k, return the kth row of the Pascal's triangle.

For example, given k = 3, Return [1,3,3,1].

Note: Could you optimize your algorithm to use only O(k) extra space?

思想: 动态规划。注意O(k)空间时,每次计算新的行时,要从右向左加。否则,会发生值的覆盖。

class Solution {
public:
    vector<int> getRow(int rowIndex) {
        vector<int> vec(rowIndex+1, 1);
        for(int i = 2; i <= rowIndex; ++i) 
            for(int j = i-1; j > 0; --j) // key, not overwrite
                vec[j] += vec[j-1];
        return vec;
    }
};