[LeetCode] 118. Pascal's Triangle

Given numRows, generate the first numRows of Pascal's triangle.

For example, given numRows = 5,
Return

[
     [1],
    [1,1],
   [1,2,1],
  [1,3,3,1],
 [1,4,6,4,1]
]
Solution:

杨辉三角,result[i][j] = result[i-1][j] + result[i-1][j-1]

Running Time:O(n2)

Space: O(n2)

class Solution:
    # @return a list of lists of integers
    def generate(self, numRows):
        if numRows <= 0 :
            return []
        result = [[1]]
        if numRows == 1:
            return result
        for i in range(1, numRows):
            temp = []
            temp.append(1)
            for j in range(1, i):#watch the index here
                temp.append(result[i-1][j-1] + result[i-1][j])
            temp.append(1)
            result.append(temp)
        return result






你可能感兴趣的:(LeetCode,python)