您的位置:首页 > 其它

compute Binomial Coefficient or combinations with dynamic programming

2014-08-23 12:17 459 查看
The Problem
Write a function that takes two parameters n and k and returns the value of Binomial Coefficient C(n, k). For example, your function should return 6 for n = 4 and k = 2, and it should return 10 for n = 5 and k = 2.

def ComputeBinomialCoefficients(n,k):
# ComputeBinomialCoefficients(5,2) shoud return 10
table = [0] * (k+1)
table[0] = 1
for i in range(1, n+1):
for j in range(min(i,k), 0, -1):       # why begin with min(i,k): 1) we do not need any results more than k. 2) Yang Hui (Pascal) Triangle: j must be less than i
table[j] = table[j] + table[j - 1]   # this comes from YANG Hui Triangle (or Pascal Trianle) of Binomial Coefficients

return table[k]


referece:
http://www.geeksforgeeks.org/dynamic-programming-set-9-binomial-coefficient/ http://en.wikipedia.org/wiki/Pascal%27s_triangle
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐