Very simple Python solution


  • 35
    A
    class Solution(object):
        def getRow(self, rowIndex):
            """
            :type rowIndex: int
            :rtype: List[int]
            """
            row = [1]
            for _ in range(rowIndex):
                row = [x + y for x, y in zip([0]+row, row+[0])]
            return row
    

    Updated according to @greg-irl 's suggestion below. It runs 30% faster than using map()


  • 1

    Can you explain you alogrithm!


  • 2
    class Solution(object):
        def factor(self, n):
            if(n <= 0):
                return 1
            factor = 1
            while(n > 0):
                factor *= n
                n -= 1
            return factor
        
        def getRow(self, RowIndex):
            """
            :type RowIndex: int
            :rtype: List[List[int]]
            """
            n = RowIndex
            if(n == 0):
                return [1]
            List = [1] * (n + 1)
            for j in range(0, n + 1):
                if(n == j):
                    List[j] = 1 
                elif(j == 0):
                    List[j] = 1
                elif(j == 1):
                    List[j] = n
                else:
                    List[j] = self.factor(n) // (self.factor(j) * self.factor(n - j))
    
            return List
    

  • 4
    A

    Say we have the current layer [1, 2, 1]. We then make 2 copies of this layer, add 0 to the start of one copy, and add 0 to the end of one copy; then we have [0, 1, 2, 1] and [1, 2, 1, 0]. Then we can perform the element-wise add operation and we would have [1, 3, 3, 1]. This is from the definition of Pascal's Triangle.


  • 0

    Thank you for you patient answers! good luck to you everyday!


  • 0
    Z

    map() returns a list.


  • 0
    A

    @zhan430 No it does not.
    According to the python docs, map() "Return an iterator that applies function to every item of iterable, yielding the results." So it returns a iterator, rather than a list.
    See: https://docs.python.org/3/library/functions.html#map


  • 1
    G

    To avoid using map(), the following is functionally equivalent and more "pythonic":

    row = [x+y for x,y in zip([0]+row, row+[0])]
    

  • 2
    A

    @greg-irl Thanks for the nice code. It is clean and actually runs faster than mine. I tested on my desktop and it's about 30% faster.


  • 0
    C

    @AntaresTsao Amazing!


  • 0

    holy...
    genius..


Log in to reply
 

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