题目来源:leetcode 118.杨辉三角 https://leetcode-cn.com/problems/pascals-triangle/
题目:
给定一个非负整数 numRows,生成杨辉三角的前 numRows 行。
在杨辉三角中,每个数是它左上方和右上方的数的和。
示例:
输入: 5
输出:
[
[1],
[1,1],
[1,2,1],
[1,3,3,1],
[1,4,6,4,1]
]
代码如下:
class Solution(object):
def generate(self, numRows):
"""
:type numRows: int
:rtype: List[List[int]]
"""
if numRows == 0:
return []
List = [[1],[1,1]]
if numRows == 1:
List = [[1]]
return List
elif numRows == 2:
return List
for i in range(2,numRows):
tmp = [1]
for j in range(1,i):
tmp.append(List[i-1][j] +List[i-1][j-1])
tmp.append(1)
List.append(tmp)
return List
扩展:
给定一个非负索引 k,其中 k ≤ 33,返回杨辉三角的第 k 行
示例:
输入: 3
输出: [1,3,3,1]
在之前代码基础改动后,代码如下:
class Solution(object):
def getRow(self, rowIndex):
"""
:type rowIndex: int
:rtype: List[int]
"""
List = [[1],[1,1]]
if rowIndex == 0:
return List[0]
if rowIndex == 1:
return List[1]
for i in range(2,rowIndex+1):
tmp = [1]
for j in range(1,i):
tmp.append(List[i-1][j] +List[i-1][j-1])
tmp.append(1)
List.append(tmp)
return List[rowIndex]
进阶:优化算法到 O(k) 空间复杂度
要做到O(k) 空间复杂度,考虑到杨辉三角每一行的值是在上一行基础上相加得来的,所以可以在List列表上不停的叠加得出下一行结果,而不用将所有行都显示出来,由于 List[n] = List[n] + List[n-1] ,无法保留上一行的 List[n-1],所以考虑从后往前叠加
class Solution(object):
def getRow(self, rowIndex):
"""
:type rowIndex: int
:rtype: List[int]
"""
List = [1]
for x in range(1,rowIndex+1):
List.append(0)#初始化
for i in range(1,rowIndex+1):
for j in range(i,0,-1):
List[j] = List[j] + List[j-1]
return List