Straightforward Python solution


  • 0

    Noticeably, the rowIndex follows zero-based numbering.

    Each row shares the same pattern that the first and last elements are 1's, and elements in the middle are the addition of adjacent pairs in one row before.

    def getRow(self, rowIndex):
        pend = [1]
        for i in xrange(rowIndex):
            pend = [1] + [pend[k] + pend[k+1] for k in xrange(len(pend) - 1)] + [1]
        return pend

  • 0
    C

    I like your very pythonic solution! Neat and clean! But I think under the hood, at each iteration, a new copy of list is created and the address is assigned to the variable pend. Maybe we should do some thing like:

    def getRow(self, rowIndex):
        pend = [1]
        for i in xrange(rowIndex):
            for ind in xrange(len(pend)-1):
                pend[ind]+=pend[ind+1]
            pend[-1]=1
            pend.insert(0,1)
        return pend
    

    I could be wrong and it's ridiculously slow.


  • 0
    Z

    This is absolutely neat but I couldn't understand it. Given i starting from 0, for ind in xrange(0): pend[0] += pend[1], why isn't there an IndexError issue when pend is still a one-element list. Sry if this is a stupid question, but I found this confusing.


  • 0
    C

    Because when len(pend) is 1, xrange(len(pend)-1) is empty.


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.