leetcode—pascal triangle

时间:2024-10-13 08:06:25

1.题目描述

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]

]

 

2.解法分析

这个题目很简单,所以不需要额外的解说,一遍就AC了

class Solution {

public:

    vector<vector<int> > generate(int numRows) {

        // Start typing your C/C++ solution below

        // DO NOT write int main() function

        //by areslipan@163.com

        vector<vector<int> > pascal;

        

        if(numRows <= 0)return pascal;

        vector<int> firstRow ;

        firstRow.push_back(1);

        pascal.push_back(firstRow);

        if(numRows == 1)return pascal;

        firstRow.push_back(1);

        pascal.push_back(firstRow);

        if(numRows == 2)return pascal;

        

        for(int i = 2;i<numRows;++i)

        {

            vector<int> curRow;

            curRow.assign(i+1,0);

            

            curRow[0]= 1;

            curRow[i] =1;

            

            for(int j =1;j<i;++j)

            {

                curRow[j]=pascal[i-1][j-1]+pascal[i-1][j];

            }

            

            pascal.push_back(curRow);

        }

        

        return pascal;

        

    }

};