欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

leetcode 119. Pascal's Triangle II 帕斯卡三角形(杨辉三角)(Python)

程序员文章站 2022-03-06 08:02:08
...

题目:

        

Given a non-negative index k where k ≤ 33, return the kth index row of the Pascal's triangle.

Note that the row index starts from 0.

leetcode 119. Pascal's Triangle II 帕斯卡三角形(杨辉三角)(Python)
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?

 

代码:

from scipy.special import comb, perm

class Solution:
    
    def getRow(self, rowIndex):
        """
        :type rowIndex: int
        :rtype: List[int]
        """
        res = []
        for i in range (0,rowIndex+1):
            res.append(int(round(comb(rowIndex,i),0)))
        return res

思路:

leetcode 119. Pascal's Triangle II 帕斯卡三角形(杨辉三角)(Python)

三角中每一行数为组合中每一项的值。如第3行是:1,3,3,1。即:

leetcode 119. Pascal's Triangle II 帕斯卡三角形(杨辉三角)(Python)

调用计算排列组合的包 from scipy.special import comb, perm来计算组合的数值。

round()函数用来计算float数值四舍五入的int值的结果。