Find the Number of Possible Ways for an Event Problem
Description
LeetCode Problem 3317.
You are given three integers n, x, and y.
An event is being held for n performers. When a performer arrives, they are assigned to one of the x stages. All performers assigned to the same stage will perform together as a band, though some stages might remain empty.
After all performances are completed, the jury will award each band a score in the range [1, y].
Return the total number of possible ways the event can take place.
Since the answer may be very large, return it modulo 10^9 + 7.
Note that two events are considered to have been held differently if either of the following conditions is satisfied:
- Any performer is assigned a different stage.
- Any band is awarded a different score.
Example 1:
Input: n = 1, x = 2, y = 3
Output: 6
Explanation:
- There are 2 ways to assign a stage to the performer.
- The jury can award a score of either 1, 2, or 3 to the only band.
Example 2:
Input: n = 5, x = 2, y = 1
Output: 32
Explanation:
- Each performer will be assigned either stage 1 or stage 2.
- All bands will be awarded a score of 1.
Example 3:
Input: n = 3, x = 3, y = 4
Output: 684
Constraints:
1 <= n, x, y <= 1000
Solution
Approach: Dynamic Programming
First count the ways to place the performers so that exactly j programs are used, then multiply by the score choices.
Let f[i][j] be the number of ways to assign the first i performers so that exactly j of the x programs are used (so the used programs are the first j ones in order of first appearance). Start with f[0][0] = 1. For the i-th performer:
- They join one of the
jprograms that already have a performer:f[i - 1][j] * jways. - They start a new program: there are
x - (j - 1)unused programs, sof[i - 1][j - 1] * (x - (j - 1))ways.
Each of the j used programs gets a score from 1 to y, which gives y^j choices. The answer is the sum over j from 1 to x of f[n][j] * y^j, taken modulo 10^9 + 7.
Complexity: O(n * x) time and O(n * x) space.
class Solution:
def numberOfWays(self, n: int, x: int, y: int) -> int:
mod = 10**9 + 7
f = [[0] * (x + 1) for _ in range(n + 1)]
f[0][0] = 1
for i in range(1, n + 1):
for j in range(1, x + 1):
f[i][j] = (f[i - 1][j] * j + f[i - 1][j - 1] * (x - (j - 1))) % mod
ans, p = 0, 1
for j in range(1, x + 1):
p = p * y % mod
ans = (ans + f[n][j] * p) % mod
return ans