2018.05.03 leetcode #119. Pascal's Triangle II
程序员文章站
2022-04-01 12:10:22
...
#119. Pascal's Triangle II
题目描述:
Given a non-negative index k where k ≤ 33, return the kth index row of the Pascal's triangle.
Note that the row index starts from 0.
返回Pascal三角指定行的数字列表
比如
# Approach 1
按照规律 每行最左侧与最右侧的数字以外,每个数字等于它的左上方与右上方两个数字之和
每次倒数第二次的迭代都新建row为n-1行的数,例如rowIndex= 3,则第i-1次迭代时row为第2行的数字。
class Solution(object):
def getRow(self, rowIndex):
row = [1]
# range(1,1)返回空列表,for不迭代
# range(0)返回空列表,for不迭代
for i in range(1, rowIndex + 1):
row = [1] + [ row[j] + row[j+1] for j in range(len(row)-1)] + [1]
return row
# Approach 2
利用
第n行的m个数可表示为C(n-1,m-1)(n-1下标,m-1上标),即为从n-1个不同元素中取m-1个元素的组合数。
组合数计算方法:C(n,m)=n!/[m!(n-m)!]
class Solution(object):
def factorial(self,n):
if n in[0,1]:
return 1
else:
return n * Solution.factorial(self, n-1)
def getRow(self, rowIndex):
row = []
for i in range(rowIndex+1):
#每一行符合组合数公式 第n行第m个数为 n!/(n! * (n-m)!)
row.append(self.factorial(rowIndex) // (self.factorial(i) * self.factorial(rowIndex - i)))
return row
推荐阅读
-
Leetcode Pascal's Triangle II
-
Pascal's Triangle II - LeetCode
-
119. Pascal‘s Triangle II
-
[LeetCode]118. Pascal's Triangle
-
Leetcode No.119 Pascal's Triangle II(c++实现)
-
LeetCode-119. Pascal's Triangle II
-
119. Pascal's Triangle II [杨辉三角形2]
-
119. Pascal's Triangle II
-
leetcode -- 119. Pascal's Triangle II
-
2018.05.03 leetcode #119. Pascal's Triangle II