118.Pascal's Triangle

August 17, 2016

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

给出行数,要求生成杨辉三角。

这道题只要找到了从第二行开始的递推公式即可,我们发现最左和最右两个数都是1,中间的数等于其“肩上”两数之和。根据组合数公式 image ,对于第k(k > 2)层第n(n > 1 && n < k)个元素A[k][n]有

A[k][n] = A[k-1][n-1] + A[k-1][n]

image

由此我们可以写出代码如下:

class Solution {
public:
    vector<vector<int>> generate(int numRows) {
        vector<vector<int>> val;
        val.resize(numRows);
        int i=0,j=0;
        for(i=0;i<numRows;i++){
            val[i].resize(i+1);
            val[i][0]=1;
            val[i][val[i].size()-1]=1;
            for(j=1;j<val[i].size()-1;j++)
                val[i][j]=val[i-1][j-1]+val[i-1][j];
        }
        return val;
    }
};
  • [ TODO 119. Pascal’s Triangle II ]

北邮教务系统评教脚本

Published on September 17, 2017

72.Edit distance

Published on September 17, 2017