Given a non-negative integer numRows, generate the first numRows of Pascal's triangle.
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] ]
楊輝三角是二項式系數的一種寫法,如果熟悉楊輝三角的五個性質,那么很好生成,可參見我的上一篇博文Pascal's Triangle II。具體生成算是:每一行的首個和結尾一個數字都是1,從第三行開始,中間的每個數字都是上一行的左右兩個數字之和。代碼如下:
class Solution { public: vector<vector<int>> generate(int numRows) { vector<vector<int>> res(numRows, vector<int>()); for (int i = 0; i < numRows; ++i) { res[i].resize(i + 1, 1); for (int j = 1; j < i; ++j) { res[i][j] = res[i - 1][j - 1] + res[i - 1][j]; } } return res; } };
類似題目:
參考資料:
https://leetcode.com/problems/pascals-triangle/
https://leetcode.com/problems/pascals-triangle/discuss/38150/My-C%2B%2B-code-0ms