# 【LeetCode】 118. Pascal's Triangle ## Description > Given a non-negative integer numRows, generate the first numRows of Pascal's triangle. > 給予一個非負整數numRows,請產生一個大小為numRows的帕斯卡三角形。 ![](https://upload.wikimedia.org/wikipedia/commons/0/0d/PascalTriangleAnimated2.gif) ## Example: ``` Example: Input: 5 Output: [ [1], [1,1], [1,2,1], [1,3,3,1], [1,4,6,4,1] ] ``` ## Solution * 第`i`列會有`i`個數字。 * 如果是第一個數字或最後一個數字,必定為`1`;否則會是上一層自己上面那兩個數字的和。 ### Code ```C++=1 class Solution { public: vector<vector<int>> generate(int numRows) { vector<vector<int>> ans; for(int i=0;i<numRows;i++) { vector<int> temp; for(int j=0;j<=i;j++) { if(j==i || j==0) { temp.push_back(1); } else { temp.push_back(ans.back()[j-1]+ans.back()[j]); } } ans.push_back(temp); } return ans; } }; ``` ###### tags: `LeetCode` `C++`