一、题目
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?
class Solution(object):
def getRow(self, rowIndex):
"""
:type rowIndex: int
:rtype: List[int]
"""
array = []
for i in range(rowIndex+1):
array.append([1]*(i+1))
for j in range(i):
array[i][j] = array[i-1][j-1] + array[i-1][j]
array[i][0] = array[i][-1] = 1
return array[rowIndex]
三、用pascal原理,注意zip的使用
class Solution(object):
def getRow(self, rowIndex):
"""
:type rowIndex: int
:rtype: List[int]
"""
row = [1]
for i in range(rowIndex):
row = [x + y for x, y in zip([0]+row,row+[0])]
return row
四、pascal三角原理
Say we have the current layer [1, 2, 1]. We then make 2 copies of this layer, add 0 to the start of one copy, and add 0 to the end of one copy; then we have [0, 1, 2, 1] and [1, 2, 1, 0]. Then we can perform the element-wise add operation and we would have [1, 3, 3, 1]. This is from the definition of Pascal's Triangle.
五、zip用法
a = [1,2,3]
b = [4,5,6]
c = [4,5,6,7,8]
zipped = zip(a,b)
>>>[(1, 4), (2, 5), (3, 6)]
zip(a,c)
>>>[(1, 4), (2, 5), (3, 6)]
zip(*zipped)
>>>[(1, 2, 3), (4, 5, 6)]
a = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
zip(*a)
>>>[(1, 4, 7), (2, 5, 8), (3, 6, 9)]
map(list,zip(*a))
>>>[[1, 4, 7], [2, 5, 8], [3, 6, 9]]