Count Ways to Distribute Candies — LeetCode 1692 Python Solution
- Problem
- #1692
- Pattern
- Dynamic Programming
- Reading time
- 2 min
- Source
- leetcode.com
The problem
There are n unique 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.
Example
- Input
- n = 3, k = 2
- Output
- 3
- Explanation
- You can distribute 3 candies into 2 bags in 3 ways:
Python solution
class Solution:
def waysToDistribute(self, n: int, k: int) -> int:
mod = 10**9 + 7
f = [[0] * (k + 1) for _ in range(n + 1)]
f[0][0] = 1
for i in range(1, n + 1):
for j in range(1, k + 1):
f[i][j] = (f[i - 1][j] * j + f[i - 1][j - 1]) % mod
return f[n][k]Complexity
| Measure | Complexity |
|---|---|
| Time | O(n \times k) |
| Space | O(n \times k) auxiliary |
Pattern: Dynamic Programming
Define a state, write the transition, and stop recomputing the same subproblem. LeetCode 1692. Count Ways to Distribute Candies is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Dynamic Programming.
The dynamic programming guide has the Python template for the pattern and the 481 LeetCode problems that use it.
Related problems
Frequently asked questions
- How hard is LeetCode 1692. Count Ways to Distribute Candies?
- LeetCode 1692. Count Ways to Distribute Candies is rated Hard on LeetCode.
- What is the time complexity of LeetCode 1692. Count Ways to Distribute Candies?
- The Python solution on this page runs in O(n \times k).
- What is the space complexity of LeetCode 1692. Count Ways to Distribute Candies?
- The Python solution on this page uses O(n \times k) auxiliary space.
- What topics does LeetCode 1692. Count Ways to Distribute Candies cover?
- LeetCode 1692. Count Ways to Distribute Candies is tagged Dynamic Programming on LeetCode.
- Is LeetCode 1692. Count Ways to Distribute Candies a premium problem?
- Yes. LeetCode 1692. Count Ways to Distribute Candies is a LeetCode Premium problem, so the full statement and test cases require a paid LeetCode subscription.