LeetCode每日练习-数组-杨辉三角(118、119)

118. 杨辉三角

输入: numRows = 5
输出: [
[1],
[1,1],
[1,2,1],
[1,3,3,1],
[1,4,6,4,1]]

class Solution:
    def generate(self, numRows: int) -> List[List[int]]:        
        # 二维数组的生成
        result = []
        # 外循环实现对元素的添加到大数组
        for i in range(numRows):
            row = []
            # 内循环实现对数组的计算
            for j in range(i+1):
                # 首元素赋值为1
                if j == 0 or j == i:
                    row.append(1)
                else:
                    row.append(result[i-1][j-1]+result[i-1][j])
            result.append(row)
        return result
119. 杨辉三角 II

给定一个非负索引 rowIndex,返回「杨辉三角」的第 rowIndex 行。
在「杨辉三角」中,每个数是它左上方和右上方的数的和。

  • 方法1:记录每个求解结果
class Solution:
    def getRow(self, rowIndex: int) -> List[int]:
        result = []
        for i in range(rowIndex+1):
            row = []
            for j in range(i+1):
                if j == 0 or j == i:
                    row.append(1)
                else:
                    row.append(result[i-1][j-1] + result[i-1][j])
            result.append(row)
        return result[-1]
  • 方法2:直接求解 降低空间复杂度
class Solution:
    def getRow(self, rowIndex: int) -> List[int]:
        result = [0]*(rowIndex+1)
        for i in range(rowIndex+1):
            # 逆序遍历
            for j in range(i, -1, -1):
                if j == 0 or j == i:
                    result[j] = 1
                # 中间值为之前元素前两个位置之和
                else:
                    result[j] = result[j] + result[j-1]
        return result

你可能感兴趣的:(LeetCode每日练习-数组-杨辉三角(118、119))