问题
Regarding the classic problem of putting N identical balls into M distinct bins and printing all the combinations: What if you would want to extend the problem by printing all cases 0< M, N
The brute force method could be done something like this:
for (int i =0; i<M; i++)
{
for (int j =0; j <N; j++)
{
PrintAllCombinations(j,i)
}
}
Now if we study the output of the first couple m and n, we see that the output of each previous iteration is a subset of the next. It seems to me that we can apply a dynamic algorithm to exploit this phenomenon. However, because we still need to partition every n
, for example n=3 = 3 +0, 2+1, 1+2
. we still need to do alot of redundant combination calculations.
Any ideas fir improvments?
回答1:
Let S[i][j]
be the number of combinations for i
balls in j
bins.
S[0][j] = 1
for all j since the only combination is to have all bins empty.
S[i][1] = 1
for all i since the only combination is to put all the balls in the one bin.
For every other i, j S[i][j] = sum(x = 0 -> i, S[i-x][j-1])
. That is for every other position you can compute the number of combinations by assigning every possible number of balls to the last bin and sum the number of combinations you get.
If you want to print out the combinations you can replace the count with the actual combinations and append the value x
when you take the internal combinations in the sum. That will take a lot of memory without a lot of gain in speed. Just do the recursion and repeat the computation since you're bound by the number of solutions anyway.
来源:https://stackoverflow.com/questions/36247061/calculating-how-many-balls-in-bins-over-several-values-using-dynamic-programming