- Trending Categories
- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP

- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who

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

3

- Related Questions & Answers
- Program to count number of ways we can distribute coins to workers in Python
- Program to count number of ways we can throw n dices in Python
- Program to count number of ways to win at most k consecutive games in Python
- Program to count number of stepping numbers of n digits in python
- Write a program in Python to count the number of digits in a given number N
- Program to count number of BST with n nodes in Python
- Count number of ways to divide a number in parts in C++
- Program to count number of paths whose sum is k in python
- Distribute Candies to People in Python
- Count number of ways to partition a set into k subsets in C++
- Golang Program to Count the Number of Digits in a Number
- Program to count the number of consistent strings in Python
- Number of Ways to Paint N × 3 Grid in C++ program
- Count the number of ways to traverse a Matrix in C++
- Program to count number of sublists with exactly k unique elements in Python

Advertisements