Program to count the number of ways to distribute n number of candies in k number of bags in Python

PythonServer Side ProgrammingProgramming

Suppose, there are n number of candies and k bags in which the candies have to put into. We have to find out the number of possible ways the candies can be distributed so that each bag contains at least one candy. Every candy in this scenario is unique, so we have to count all the possible ways the candies can be distributed in the bags.

So, if the input is like n = 3, k = 2, then the output will be 3.

The candies can be put in this manner −

(1, 2), (3)
(1) , (2, 3)
(2), (1, 3)

To solve this, we will follow these steps −

  • dp := a matrix of size n x n initialized with value 1

  • for c in range 2 to n, do

    • for b in range 1 to minimum of (c, k), do

      • dp[c, b] := dp[c-1, b-1] + dp[c-1, b] * (b+1)

  • return dp[n-1, k-1]


Let us see the following implementation to get better understanding −

def solve(n, k):
   dp = [[1] * n for _ in range(n)]
   for c in range(2, n):
      for b in range(1,min(c,k)):
         dp[c][b] = dp[c-1][b-1] + dp[c-1][b] * (b+1)
   return dp[n-1][k-1]

print(solve(3, 2))


3, 2


Updated on 08-Oct-2021 07:27:51