Distribution of balls into 'bins with given capacities' using Dynamic Programming

痴心易碎 提交于 2019-12-05 06:40:39

You can define your function assuming the limits c[0], c[1], ... c[m-1] as fixed and then writing the recursive formula that returns the number of ways you can distribute n balls into bins starting at index k. With this approach a basic formula is simply

def solutions(n, k):
    if n == 0:
        return 1  # Out of balls, there's only one solution (0, 0, 0, 0 ... 0)
    if k == m:
        return 0  # Out of bins... no solutions
    total = 0
    for h in xrange(0, min(n, c[k])+1): # from 0 to c[k] (included) into bin k
        total += solutions(n - h, k + 1)
    return total

then you need to add memoization (this will be equivalent to a DP approach) and some other optimizations like e.g. that if n > c[k] + c[k+1] + c[k+2] + ... then you know there are no solutions without the need to search (and you can precompute the partial sums).

  1. There exists a combinatoric formula for this problem. The problem of finding the solutions to your problem is equivalent to finding the number of solutions of the equation
    x1 + x2 + x3 + ... + xm = n
    where xi < ci
    Which is equivalent to finding the cofficient of x^n in the following equation
    (1+x+..x^c1)(1+x+..+x^c2)...(1+x+...+x^cm)

  2. The recursion for this equation is pretty simple
    M(i,j) = summation(M(i-1, j-k)) where 0<= k <= cj M(i,j) = 0 j <= 0 M(i,1) = i given for every 1= 1 M(i,j) is the number of ways of distributing the j balls in first i bins.

For the Dynamic Programming part Solve this recursion by Memoization, You will get your DP Solution automatically.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!