C++實現LeetCode(118.楊輝三角)

[LeetCode] 118.Pascal’s Triangle 楊輝三角

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;
    }
};

類似題目:

Pascal’s Triangle II

參考資料:

https://leetcode.com/problems/pascals-triangle/

https://leetcode.com/problems/pascals-triangle/discuss/38150/My-C%2B%2B-code-0ms

到此這篇關於C++實現LeetCode(118.楊輝三角)的文章就介紹到這瞭,更多相關C++實現楊輝三角內容請搜索WalkonNet以前的文章或繼續瀏覽下面的相關文章希望大傢以後多多支持WalkonNet!

推薦閱讀: