Try   HackMD

【LeetCode】 119. Pascal's Triangle II

Description

Given a non-negative index k where k ≤ 33, return the kth index row of the Pascal's triangle.
Note that the row index starts from 0.

給予一個非負數索引值k,且k ≤ 33,回傳帕斯卡三角形中的第k列。
注意,索引從零開始。

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:

Input: 3
Output: [1,3,3,1]

Solution

  • 可以直接拿118. Pascal’s Triangle簡單改一下就好,基本上是一樣的問題。
  • 118題的code,改成只輸出最後一列即可。

Code

class Solution { public: vector<int> getRow(int rowIndex) { vector<int> ans; for(int i=0;i<=rowIndex;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[j-1]+ans[j]); } } ans=temp; } return ans; } };
tags: LeetCode C++