It's the Xinrui Ma


119. Pascal’s Triangle II

Posted by in LeetCode on

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.

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?


Start to fill the array from end to beginning, that’s the key

result[j] = result[j-1]+result[j]

So j depends on the previous element in the array, if we fill the array from beginning to end, the previous element will be changed, if we start from the end, and result[j] all set to 0 at first except result[0] = 1, result[j]’s value won’t get changed during the loop.

Space complexity is O(k), time complexity is O(n2).