2021-02-12 Leetcode每日刷题
题目
Given an integer rowIndex, return the rowIndexth row of the Pascal’s triangle.
Notice that the row index starts from 0.
In Pascal’s triangle, each number is the sum of the two numbers directly above it.
Follow up: Could you optimize your algorithm to use only O(k) extra space?
Example 1:
Input: rowIndex = 3
Output: [1,3,3,1]
Constraints:
0 <= rowIndex <= 33
我的思路
基本思路是写出第j行第i个数的表达式。第0个数和第j+1个数都为1,其余的值为第j-1行第i-1个数和第i个数的和。据此写出以下代码:
class Solution:
def getRow(self, rowIndex: int) -> List[int]:
k = rowIndex
Pascal = []
for j in range(0,k+1):
krow = []
for i in range(j):
if i == 0:
krow.append(1)
else:
val = Pascal[j-1][i-1]+Pascal[j-1][i]
krow.append(val)
krow.append(1)
print(krow)
Pascal.append(krow)
print(Pascal[k])
return Pascal[k]
提交结果:
补充:
参考思路:
看了眼别人的代码,我写的是什么垃圾。
这个思路是递推,从第i-1行算出第i行,这样每次算一行的时间复杂度都是线性的。空间复杂度 O(k * (k + 1) / 2)O(k∗(k+1)/2)。
但是这个题目有奇淫技巧:只使用一个一维数组计算,每行在末尾多加个1,然后第j个数字的值 +=第j-1数字的值,以此更新每行的数字。空间复杂度O(k)
(依旧是看的负雪明烛的思路,我的输入法都认识这位大神了。BTW加了打卡群,希望可以坚持下去。)
代码:
class Solution:
def getRow(self, rowIndex: int) -> List[int]:
res = [1]*(rowIndex+1)
for i in range(2,rowIndex+1):
for j in range(i-1,0,-1):
res[j]+=res[j-1]
return res
range(start,end,step)
提交结果: