二维数组的生成-【leetcode118- 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]
]

二、解法

2.1 渣渣法一

        array = [[1 for j in range(i)]for i in range(1,numRows+1)]
        for i in range(1,numRows):
	        for j in range(i):
		        array[i][j] = array[i-1][j-1] + array[i-1][j]
		        array[i][0] = array[i][-1] = 1
        return array
2.2 改进法二

class Solution(object):
    def generate(self, numRows):
        """
        :type numRows: int
        :rtype: List[List[int]]
        """
        array = [] 
        for i in range(numRows):	
	        array.append([1]*(i+1)) 
	        for j in range(i):
		        array[i][j] = array[i-1][j-1] + array[i-1][j]
		        array[i][0] = array[i][-1] = 1
        return array


三、改进

通过法二第2、4行的改进,使得二维数组的初始化时间减少,由O(n2)变成O(n)

你可能感兴趣的:(python)