Given a non-negative index k where k ≤ 33, return the k-th index row of the Pascal’s triangle.
Note that the row index starts from 0.
给一个非负的下标k,返回第k行的帕斯卡三角形的数值
In Pascal’s triangle, each number is the sum of the two numbers directly above it.
Example:
Input: 3
Output: [1,3,3,1]
Follow up:
Could you optimize your algorithm to use only O(k) extra space?
python实践:
#!/usr/bin/env python
# _*_ coding:utf-8 _*_
# input:输入是行数
# output:输出是一个列表,该行的数值
class Solution(object):
def getRow(self, rowIndex):
"""
:type rowIndex: int
:rtype: List[int]
"""
# 首先初始化一个列表l,里面所有的元素都是1,列表长度为row+1
l = [1]*(rowIndex+1)
print(l)
if (rowIndex <= 1):
return l
last = 1
for i in range(2, rowIndex + 1):
for j in range(1, i):
temp = l[j]
l[j] = last + l[j]
last = temp
print(l)
if __name__ == '__main__':
Solution().getRow(4)
运行结果:
[1, 4, 6, 4, 1]