title: Pascals Triangle II
tags:
- pascals-triangle-ii
- No.119
- simple
- discrete-mathematics
- overflow
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.
imgIn 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?
Corner Cases
0
- huge number
30
Solutions
Naive
Use the recursive relationship bellow:
\binom{n}{k+1} = \binom{n}{k} \times \frac{n-k}{k+1} \in \mathbb{N}
Use type Long
since the integer overflows when n is big.
The time complexity and space complexity are all O(n):
class Solution {
public List<Integer> getRow(int rowIndex) {
List<Integer> lst = new LinkedList<>();
if (rowIndex == 0) {lst.add(1);return lst;}
long cni = 1;
lst.add((int)cni);
for (int i=0; i<rowIndex; i++) {
cni = cni*(rowIndex-i)/(i+1);
lst.add((int)cni);
}
return lst;
}
}
网友评论