Pacal'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) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
        vector<vector<int>> matrix;
        
        for(int i = 0; i < numRows; i++){
            
            vector<int> row;
            if (0 == i){
                row.push_back(1);
                matrix.push_back(row);
            }else{
                row = matrix[i-1];
                vector<int> new_row;
                new_row.push_back(1);
                
                for(size_t j = 0; j + 1 < row.size(); j++){
                    new_row.push_back(row[j] + row[j + 1]);
                }
                
                new_row.push_back(1);
                matrix.push_back(new_row);
            }
        }
        
        return matrix;
        
    }
};

 类似于DP压缩空间的思想,从后往前(因为下一行总是多一个元素)

class Solution {
public:    
       void f(int rowIndex,vector<int> & ans){
        for (int i = 1; i <= rowIndex; i++){
            ans[0] = 1;
            //下一行比上一行多一个元素,所以从后往前正好不会覆盖
            for(int j = i-1; j >= 1; j--){
                ans[j] = ans[j] + ans[j-1];
            }
            ans[i] = 1;
        }
    }
    vector<int> getRow(int rowIndex) {
        vector<int> ans(rowIndex + 1,0);
        ans[0] = 1;
        f(rowIndex,ans);
        return ans;    
    }
};

 

posted @ 2013-02-13 19:26  一只会思考的猪  阅读(140)  评论(0编辑  收藏  举报