Pascal's Triangle II

Question

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?

Tags

  • Array

Thought

Follow the previous problem and use the prev_row and current_row to represent the whole result.

Code

class Solution(object):
    def getRow(self, rowIndex):
        """
        :type rowIndex: int
        :rtype: List[int]
        """
        current_row = [1]
        for i in xrange(rowIndex + 1):
            prev_row = current_row
            current_row = [0 for _ in xrange(i + 1)]
            current_row[0] = 1
            current_row[-1] = 1
            for j in xrange(1, i):
                current_row[j] = prev_row[j - 1] + prev_row[j]
        return current_row

results matching ""

    No results matching ""