Try   HackMD

【LeetCode】 118. Pascal's Triangle

Description

Given a non-negative integer numRows, generate the first numRows of Pascal's triangle.

給予一個非負整數numRows,請產生一個大小為numRows的帕斯卡三角形。

Image Not Showing Possible Reasons
  • The image file may be corrupted
  • The server hosting the image is unavailable
  • The image path is incorrect
  • The image format is not supported
Learn More →

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

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++