题目描述:
给定一个非负索引 rowIndex
,返回「杨辉三角」的第 rowIndex
行。
在「杨辉三角」中,每个数是它左上方和右上方的数的和。
方法一:在上一题的基础上,返回指定行的数据
class Solution(object):
def getRow(self, rowIndex):
"""
:type rowIndex: int
:rtype: List[int]
"""
if rowIndex == 0:
return [1]
if rowIndex == 1:
return [1, 1]
result = [[0] for i in range(rowIndex + 1)]
result[0] = [1]
result[1] = [1, 1]
i = 2
while i <= rowIndex:
result[i].insert(0, 1)
j = 1
while j < i:
temp = (result[i - 1][j - 1] + result[i - 1][j])
result[i].insert(j, temp)
j += 1
result[i][i] = 1
i += 1
return result[rowIndex]
方法二:结合杨辉三角的数学特性,不需要求出整个二位数组,只需要求出指定行的结果就行。
杨辉三角性质:
- 每行数字左右对称,由 1 开始逐渐变大再变小,并最终回到 1。
- 第 n 行(从 0 开始编号)的数字有 n+1 项,前 n 行共有
个数。
- 第 n 行的第 m 个数(从 0 开始编号)可表示为组合数
,记作
或
,即为从 n 个不同元素中取 m 个元素的组合数。我们可以用公式来表示它:
![]()
- 每个数字等于上一行的左右两个数字之和,可用此性质写出整个杨辉三角。即第 n 行的第 i 个数等于第 n-1 行的第 i−1 个数和第 i 个数之和。这也是组合数的性质之一,即
![]()
的展开式(二项式展开)中的各项系数依次对应杨辉三角的第 n 行中的每一项。
作者:LeetCode-Solution
链接:https://leetcode-cn.com/problems/pascals-triangle-ii/solution/yang-hui-san-jiao-ii-by-leetcode-solutio-shuk/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
因此,我们可以利
class Solution(object):
def getRow(self, rowIndex):
"""
:type rowIndex: int
:rtype: List[int]
"""
# 用一个一维列表来存放结果
result = [1]
for i in range(rowIndex):
result.append(1)
j = 1
# 记录上一行数据并更新
temp1 = result[j - 1]
temp2 = result[j]
while j < len(result) - 1:
result[j] = temp1 + temp2
temp1 = temp2
j += 1
temp2 = result[j]
return result
用性质4来计算。