Python 4 lines short solution using map.


  • 77
    T
    def generate(self, numRows):
            res = [[1]]
            for i in range(1, numRows):
                res += [map(lambda x, y: x+y, res[-1] + [0], [0] + res[-1])]
            return res[:numRows]
    

    explanation: Any row can be constructed using the offset sum of the previous row. Example:

        1 3 3 1 0 
     +  0 1 3 3 1
     =  1 4 6 4 1

  • 0
    B

    awesome code !!!


  • 0
    W

    Brilliant Code


  • 2
    L
    class Solution(object):
        def generate(self, numRows):
            """
            :type numRows: int
            :rtype: List[List[int]]
            if numRows = 5
                   [
                         [1],
                        [1,1],
                       [1,2,1],
                      [1,3,3,1],
                     [1,4,6,4,1]
                   ]
            """
    
            num = [[1], [1, 1]]
            if numRows == 1:
                return num[0]
            elif numRows == 2:
                return num
            elif numRows == 0:
                return []
            
            row = []
            for i in range(2, numRows):
                for j in range(i - 1):
                    row.append(sum(num[-1][j:j + 2]))
                num.append([1] + row + [1])
                row = []
    
            return num
    

  • 0

    why return "res[:numRows]" but not "res" ?


  • 0
    T

    It's used to handle the case when numRows = 0.


  • 0

    yes, i tried the 0 case, if return res, would get the wrong result [[1]]. thanks for your prompt


  • 0
    Q
    This post is deleted!

  • 0
    S
    This post is deleted!

  • 0
    P
    class Solution(object):
        def generate(self, numRows):
            """
            :type numRows: int
            :rtype: List[List[int]]
            """        
            res = [[1]]
            for i in range(1, numRows):
                res.append(map(lambda x,y: x+y, [0]+res[-1], res[-1]+[0]))
            return res if numRows else []
    

    Almost the same code, but your way to deal with the case numRows=0 is better LOL


  • 0
    0

    Just Pythonic!!!


  • 1
    B

    How can you add an int and a list here?

    res += [map(lambda x, y: x+y, res[-1] + [0], [0] + res[-1])]


  • 0
    B

    @belozi said in Python 4 lines short solution using map.:

    res[-1] + [0]

    res[-1] is a list of number, it appends one more element "0"


Log in to reply
 

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