Tuesday, September 23, 2014

Leetcode: Pascal's Triangle II

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?

Understand the problem:The problem is an extension of the Pascal's Triangle I. The mainly difference is it only asks you output the kth row of the triangle. Note that k starts from 0. One straight-forward solution is to generate all rows of the Pascal's triangle until the kth row. In this way the complexity is O(k^2). However the problem asks for using only O(k) extra space. Solution:Note that in the previous solution for Problem I, we only need to results for current and its previous row. That means we only need to maintain these two rows, where the space complexity is still O(k).Code (Java):

Discussion:For the solution above, it takes O(k) space but takes O(n^3) time because the copy of array operations. We need to think of a better solution.A better solution:Note that for a[j] = a[j] + a[j - 1], so for each a[j] we can update a[j] from the last a[j] and a[j - 1]. However, if we don't store the previous result, the updated value will pollute the later on numbers. So one solution is to update each number in the row from end in a backward order.Code (Java):