There are nunique candies (labeled 1 through n) and k bags. You are asked to distribute all the candies into the bags such that every bag has at least one candy.
There can be multiple ways to distribute the candies. Two ways are considered
different if the candies in one bag in the first way are not all in the same bag in the second way. The order of the bags and the order of the candies within each bag do not matter.
For example, (1), (2,3) and (2), (1,3) are considered different because candies 2 and 3 in the bag (2,3) in the first way are not in the same bag in the second way (they are split between the bags (_2_) and (1,_3_)).
However, (1), (2,3) and (3,2), (1) are considered the same because the candies in each bag are all in the same bags in both ways.
Given two integers, n and k, return thenumber of different ways to distribute the candies. As the answer may be too large, return it modulo109 + 7.

Input: n =3, k =2Output: 3Explanation: You can distribute 3 candies into 2 bags in3 ways:(1),(2,3)(1,2),(3)(1,3),(2)
Example 2:
1
2
3
4
5
6
7
8
9
10
Input: n =4, k =2Output: 7Explanation: You can distribute 4 candies into 2 bags in7 ways:(1),(2,3,4)(1,2),(3,4)(1,3),(2,4)(1,4),(2,3)(1,2,3),(4)(1,2,4),(3)(1,3,4),(2)
Example 3:
1
2
3
Input: n =20, k =5Output: 206085257Explanation: You can distribute 20 candies into 5 bags in1881780996 ways.1881780996 modulo 109+7=206085257.
The key idea is to count the number of ways to partition n unique candies into k non-empty bags, where the order of bags doesn’t matter, but the distribution of candies does. This is exactly the Stirling numbers of the second kind, S(n, k).
classSolution {
publicintcountWays(int n, int k) {
int MOD = 1000000007;
int[][] dp =newint[n+1][k+1];
dp[0][0]= 1;
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= k; j++) {
dp[i][j]= (int)(((long)j * dp[i-1][j]% MOD + dp[i-1][j-1]) % MOD);
}
}
return dp[n][k];
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
classSolution {
funcountWays(n: Int, k: Int): Int {
val MOD = 1_000_000_007
val dp = Array(n+1) { IntArray(k+1) }
dp[0][0] = 1for (i in1..n) {
for (j in1..k) {
dp[i][j] = ((j.toLong() * dp[i-1][j] % MOD + dp[i-1][j-1]) % MOD).toInt()
}
}
return dp[n][k]
}
}
1
2
3
4
5
6
7
8
9
classSolution:
defcountWays(self, n: int, k: int) -> int:
MOD =10**9+7 dp: list[list[int]] = [[0] * (k+1) for _ in range(n+1)]
dp[0][0] =1for i in range(1, n+1):
for j in range(1, k+1):
dp[i][j] = (j * dp[i-1][j] + dp[i-1][j-1]) % MOD
return dp[n][k]
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
impl Solution {
pubfncount_ways(n: i32, k: i32) -> i32 {
let n = n asusize;
let k = k asusize;
let m =1_000_000_007;
letmut dp =vec![vec![0; k+1]; n+1];
dp[0][0] =1;
for i in1..=n {
for j in1..=k {
dp[i][j] = ((j asi64* dp[i-1][j] asi64% m + dp[i-1][j] asi64) % m) asi32;
}
}
dp[n][k]
}
}