
1、求楊輝三角的第m行第k個元素
第m行有m項,m是正整數,因此k一定不會大于m
第n行的m個數可表示為C(n-1, m-1),即為從n-1個不同元素中取m-1個元素的組合數
解答:
#算法1:首尾補1
m = 5
k = 4
triangle = [] #使用嵌套結構[[]]
for i in range(m):
row = [1]
triangle.append(row)
if i == 0: #第0行直接返回
continue
for j in range(1,i):
row.append(triangle[i-1][j-1] + triangle[i-1][j])
row.append(1)
print(triangle)
print(“—————-“)
print(triangle[m-1][k-1])
#算法2:組合數公式
參考:【圖文】楊輝三角與組合數性質_百度文庫 https://wenku.baidu.com/view/244b7925482fb4daa58d4b1d.html

#組合數公式C(m,n) = m!/(n!(m-n)!)
#m行k列的值,C(m-1,k-1)組合數
m = 9
k = 5
#c(n,r) = c(m-1,k-1) = (m-1)!/((k-1)!(m-r)!)
n = m – 1
r = k – 1
d = n – r
targets = [] #r, n-r, n
factorial = 1
for i in range(1, n+1):
factorial *= i
if i == r:
targets.append(factorial)
if i == d:
targets.append(factorial)
if i == n:
targets.append(factorial)
print(targets)
print(targets[2]//(targets[0]*targets[1]))
本文來自投稿,不代表Linux運維部落立場,如若轉載,請注明出處:http://www.www58058.com/95591