leetcode || 118、Pascal's Triangle

problem:

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]
]

Hide Tags
  Array
题意:帕斯卡三角形,又名杨辉三角形,是多项式(a+b)^n的系数

thinking:

(1)杨辉三角形,从第三行开始,排除第一个和最后一个1外,其值是上一行上面的两个元素值之和。参考:维基百科-杨辉三角形

(2)从第三行开始,每一行的元素由上一行的元素决定

code:

class Solution {
private:
    vector > ret;
public:
    vector > generate(int numRows) {
        vector row1(1,1);
        vector row2(2,1);
        ret.clear();
        if(numRows==0)
            return ret;
        if(numRows==1)
        {
            ret.push_back(row1);
            return ret;
        }
        if(numRows==2)
        {
            ret.push_back(row1);
            ret.push_back(row2);
            return ret;
        }
        ret.push_back(row1);
        ret.push_back(row2);
        for(int i=3;i<=numRows;i++)
        {
            vector tmp;
            vector pre=ret[i-2];
            tmp.push_back(1);
            for(int j=0;j


你可能感兴趣的:(leetcode,杨辉三角形,帕斯卡三角形,LeetCode)