118. Pascal's Triangle II
Question:
Given an integer rowIndex, return the rowIndex^th row of the Pascal's triangle. Notice that the row index starts from 0. In Pascal's triangle, each number is the sum of the two numbers directly above it.
Follow up: Could you optimize your algorithm to use only O(k) extra space?
Example:
Input: rowIndex = 3
Output: [1,3,3,1]
Input: rowIndex = 0
Output: [1]
Input: rowIndex = 0
Output: [1]
Source code
Version 1
Idea:
It is familiar with Pascal's Trangle question, you can use similar algorithm to implement it.
However, the efficiency of algorithm is not optimization.
Time complexity: O(rowIndex2)
Space complexity: O(rowIndex) // <- O(rowIndexx + 1>
1 | class Solution { |
Version 2
Idea:
Here's the best algorithm.
At first, declare a vector that consists rowIndex + 1
elements. Must be add 1, because row index starts from 0. So the size of vector is ready, we don't use push_back()
in loop anymore.
Whatever a value of rowIndex is, the first position of vector is always 1, so we pass 1 to res
vector.
At 9 line, we calculate each elements in reverse(it not includes the frist element).
E.g., Input: rowIndex = 2
i = 1, res=[1, 0, 0]
i = 1, res=[1, 0 + 1, 0] = [1, 1, 0]
i = 2, res=[1, 1 + 1, 0 + 1] = [1, 2, 1] (output)
1 | class Solution { |