如何有效地计算一个行杨辉三角? [英] How to efficiently calculate a row in pascal's triangle?
问题描述
我感兴趣的是找到帕斯卡三角的第n行(而不是一个特定的元素,但整行本身)。什么是最有效的方法来做到这一点?
我想到了通过总结行中的相应元素上方将采取构建三角形的常规方式:
1 + 2 + ... + N =为O(n ^ 2)
的另一种方式可以是使用一个特定的元素的组合式:
C(N,K)= N! /(K!(N-K)!)
该行中的每个元素,我想会需要更多的时间,这取决于计算相结合的方式,前一种方法。任何想法?
>>>高清帕斯卡(N):
...行= [1]
......对于k的范围(N):
... line.append(行[k]的*(N-K)/(K + 1))
...回线
...
>>>帕斯卡(9)
[1,9,36,84,126,126,84,36,9,1]
本使用以下标识:
C(N,K + 1)= C(N,K)*(N-K)/(K + 1)
所以,你可以用启动C(N,0)= 1
,然后使用这个身份,每次previous元素相乘计算该行的其余部分通过(NK)/(K + 1)
。
I'm interested in finding the nth row of pascal triangle (not a specific element but the whole row itself). What would be the most efficient way to do it?
I thought about the conventional way to construct the triangle by summing up the corresponding elements in the row above which would take:
1 + 2 + .. + n = O(n^2)
Another way could be using the combination formula of a specific element:
c(n, k) = n! / (k!(n-k)!)
for each element in the row which I guess would take more time the the former method depending on the way to calculate the combination. Any ideas?
>>> def pascal(n):
... line = [1]
... for k in range(n):
... line.append(line[k] * (n-k) / (k+1))
... return line
...
>>> pascal(9)
[1, 9, 36, 84, 126, 126, 84, 36, 9, 1]
This uses the following identity:
C(n,k+1) = C(n,k) * (n-k) / (k+1)
So you can start with C(n,0) = 1
and then calculate the rest of the line using this identity, each time multiplying the previous element by (n-k) / (k+1)
.
这篇关于如何有效地计算一个行杨辉三角?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!