当前位置 : 主页 > 编程语言 > java >

【Leetcode 118】杨辉三角

来源:互联网 收集:自由互联 发布时间:2022-06-30
题目描述 题解 class Solution : def generate ( self , num_rows ): triangle = [] for row_num in range ( num_rows ): # The first and last row elements are always 1. row = [ None for _ in range ( row_num + 1 )] row [ 0 ], row [ - 1 ] = 1

题目描述

【Leetcode 118】杨辉三角_Java
【Leetcode 118】杨辉三角_Java_02

题解

class Solution:
def generate(self, num_rows):
triangle = []

for row_num in range(num_rows):
# The first and last row elements are always 1.
row = [None for _ in range(row_num+1)]
row[0], row[-1] = 1, 1

# Each triangle element is equal to the sum of the elements
# above-and-to-the-left and above-and-to-the-right.
for j in range(1, len(row)-1):
row[j] = triangle[row_num-1][j-1] + triangle[row_num-1][j]

triangle.append(row)
return triangle


上一篇:【Java】Arraylist综合案例斗地主
下一篇:没有了
网友评论