美文网首页
118. Pascal's Triangle

118. Pascal's Triangle

作者: SilentDawn | 来源:发表于2018-06-25 21:40 被阅读0次

Problem

Given a non-negative integer numRows, generate the first numRows of Pascal's triangle.


PascalTriangleAnimated2.gif

In Pascal's triangle, each number is the sum of the two numbers directly above it.

Example

Input: 5
Output:
[
     [1],
    [1,1],
   [1,2,1],
  [1,3,3,1],
 [1,4,6,4,1]
]

Code

static int var = [](){
    std::ios::sync_with_stdio(false);
    cin.tie(NULL);
    return 0;
}();
class Solution {
public:
    vector<vector<int>> generate(int numRows) {
        vector<vector<int>> res;   
        if(numRows>=1){
            vector<int> temp;
            temp.push_back(1);
            res.push_back(temp);
        }
        if(numRows>=2){
            for(int i=0;i<numRows-1;i++){
                vector<int> temp;
                temp.push_back(1);
                for(int j=0;j<i;j++){
                    temp.push_back(res[i][j]+res[i][j+1]);
                }
                temp.push_back(1);
                res.push_back(temp);
            }
        }
        return res;
    }
};

Result

118. Pascal's Triangle.png

相关文章

网友评论

      本文标题:118. Pascal's Triangle

      本文链接:https://www.haomeiwen.com/subject/mgjuyftx.html