Problem
1. Given numRows, generate the first numRows of Pascal's triangle. For example, given numRows = 5, return
[
[1],
[1,1],
[1,2,1],
[1,3,3,1],
[1,4,6,4,1]
]
2. Given an index k, return the kth row of the Pascal's triangle. For example, given k = 3, return [1,3,3,1].
Note: Could you optimize your algorithm to use only O(k) extra space?
Algorithm
The kth number of the nth row of the Pascal's triangle is simply C(n, k).
C(n, k) = n * ... * (n-k) / k!
Note, how to use long type to avoid overflow in the computation.
In the second problem, we can use the similar technique in problem 1. We only need to store the previous row.
C(n, k) = n * ... * (n-k) / k!
Note, how to use long type to avoid overflow in the computation.
In the second problem, we can use the similar technique in problem 1. We only need to store the previous row.
No comments:
Post a Comment