题目:
Given an index k, return the kth row of the Pascal's triangle.
For example, given k = 3,
Return [1,3,3,1]
.
Note:
Could you optimize your algorithm to use only O(k) extra space?
题解:
杨辉三角形
1
1 1
1 2 1
1 3 3 1
....
发现
1. 第一个位置为1
2. 新增的数字为1
3. 其他位置的值为当前值加上它前面的那个值
注意,O(k)空间情况下,要从后向前遍历,这样才能保证你加你前面那个数字的时候,那个数字还是旧一行的。如果从前向后的话,你处理后面的值的时候,这个值前面的数字已经更新为新的值了,就错了。
Code:
class Solution:
# @return a list of integers
def getRow(self, rowIndex):
a = [1]
k = 0;
while rowIndex > k:
k+=1
for i in range(1,k)[::-1]:
a[i] = a[i]+a[i-1]
a.append(1)
return a