Pascal's Triangle II
Given a non-negative index k where k≤ 33, return the _k_th index row of the Pascal's triangle.
Note that the row index starts from 0.
In Pascal's triangle, each number is the sum of the two numbers directly above it.
Example:
Input:
3
Output:
[1,3,3,1]Follow up:
Could you optimize your algorithm to use only O(k) extra space?
Analysis
Dynamic Programming
Same as Pascal's Triangle I, just need to use current row and previous row in order to get O(k) space complexity.
Math
Or using math (https://leetcode.com/problems/pascals-triangle-ii/discuss/38513/My-clean-O(k)-java-solution?orderBy=most_votes\:
row k of Pascal's Triangle:
[C(k,0), C(k,1), ..., C(k, k-1), C(k, k)]
and
C[k,i] = C[k,i-1]*(k-i+1)/i
Solution
O(K) space O(K^2) time (3ms 11.27%) - 在首位加1,内层循环正序即可
Same approach - Another One 在末尾加1, 内层循环要从末尾倒序循环
O(K) space and O(K) time using Math (1ms 91.55%)
O(K) space and O(K^2) (0ms 100%)
Traditional 2D DP - storing dp[][] element for each layer - O(n^2) time, and O(n^2) space - (1ms AC)
Reference
Wikipedia: [Pascal's Triangle]([https://en.wikipedia.org/wiki/Pascal's_triangle](https://en.wikipedia.org/wiki/Pascal's_triangle)\)
Last updated
Was this helpful?