且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

使用动态编程计算在多个值的箱中有多少个球

更新时间:2023-11-08 19:46:52

S [i] [j] i 球在中的组合数> j 个垃圾箱.

S [0] [j] = 1 ,因为唯一的组合是将所有垃圾箱都清空.

S[0][j] = 1 for all j since the only combination is to have all bins empty.

S [i] [1] = 1 ,因为唯一的组合就是将所有球都放在一个箱中.

S[i][1] = 1 for all i since the only combination is to put all the balls in the one bin.

对于每隔一个i,j S [i] [j] = sum(x = 0-> i,S [i-x] [j-1]).也就是说,对于每个其他位置,您可以通过将每个可能的球数分配给最后一个箱并求和得到的组合数来计算组合数.

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.

如果要打印出组合,可以将计数替换为实际组合,并在将内部组合作为总和时附加值 x .这将占用大量内存,而速度却不会大大提高.只需进行递归并重复计算,因为无论如何您都会受到解决方案数量的限制.

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.