C++實現(xiàn)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]
]
楊輝三角是二項式系數(shù)的一種寫法,如果熟悉楊輝三角的五個性質(zhì),那么很好生成,可參見另一篇博文Pascal's Triangle II。具體生成算是:每一行的首個和結(jié)尾一個數(shù)字都是1,從第三行開始,中間的每個數(shù)字都是上一行的左右兩個數(shù)字之和。代碼如下:
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
到此這篇關于C++實現(xiàn)LeetCode(118.楊輝三角)的文章就介紹到這了,更多相關C++實現(xiàn)楊輝三角內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
解決Visual?Studio?Code錯誤Cannot?build?and?debug?because?
這篇文章主要為大家介紹了解決Visual?Studio?Code錯誤Cannot?build?and?debug?because?the及分析,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2023-07-07
C++實現(xiàn)LeetCode(101.判斷對稱樹)
這篇文章主要介紹了C++實現(xiàn)LeetCode(101.判斷對稱樹),本篇文章通過簡要的案例,講解了該項技術的了解與使用,以下就是詳細內(nèi)容,需要的朋友可以參考下2021-07-07

