[Python LeetCode]118. 杨辉三角(yangyang)

题目:

[Python LeetCode]118. 杨辉三角(yangyang)_第1张图片
1.临界时,元素值为1
2.一般情况下:
triangle[i][j]=triangle[i-1][j-1]+triangle[i-1][j]

class Solution:
    def generate(self, numRows: int) -> List[List[int]]:
        #一般情况下:num[i][j]=num[i-1][j-1]+num[i-1][j]        
        triangle= [[0 for i in range(0, numRows)] for j in range(0, numRows)]
        for i in range(numRows):
            for j in range(numRows):
                if j==0 or j==i:
                    triangle[i][j]=1
                else:
                    triangle[i][j]=triangle[i-1][j-1]+triangle[i-1][j]
        for i in range(0, numRows):
            triangle[i][:] = triangle[i][:i+1]
        return triangle

总结:利用list创建mXn的矩阵
triangle= [[0 for i in range(0, n)] for j in range(0, m)]

杨辉三角2:

class Solution:
    def getRow(self, rowIndex: int) -> List[int]:
        rowIndex=rowIndex+1
        triangle=[[0 for i in range(rowIndex)] for i in range(rowIndex)]
        for i in range(rowIndex):
            for j in range(rowIndex):
                if j==0 or j==i:
                    triangle[i][j]=1
                else:
                    triangle[i][j]= triangle[i-1][j-1]+ triangle[i-1][j]
        return triangle[-1][:]

你可能感兴趣的:(leetcode,Python,leetcode)