- Define precisely what one DP state represents.
- Establish the base cases before transitions are evaluated.
- Process states in dependency order and combine only already-known values.
Code notes
- 40 lines of Python from the credited upstream file 1655.py.
- The implementation visibly relies on sequence storage, hash lookup, cached states.
- No explicit loop blocks detected.
Complexity
Multiply the number of reachable states by the work performed for each transition, then include the stored state table in memory usage.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
1class Solution:2 def canDistribute(self, nums: list[int], quantity: list[int]) -> bool:3 freqs = list(collections.Counter(nums).values())4 5 6 validDistribution = self._getValidDistribution(freqs, quantity)7 n = len(freqs)8 m = len(quantity)9 maxMask = 1 << m10 11 12 dp = [[False] * maxMask for _ in range(n + 1)]13 dp[n][maxMask - 1] = True14 15 for i in range(n - 1, -1, -1):16 for mask in range(maxMask):17 dp[i][mask] = dp[i + 1][mask]18 availableMask = ~mask & (maxMask - 1)19 submask = availableMask20 while submask > 0:21 if validDistribution[i][submask]:22 dp[i][mask] = dp[i][mask] or dp[i + 1][mask | submask]23 submask = (submask - 1) & availableMask24 25 return dp[0][0]26 27 def _getValidDistribution(self, freqs: list[int],28 quantity: list[int]) -> list[list[bool]]:29 maxMask = 1 << len(quantity)30 validDistribution = [[False] * maxMask for _ in range(len(freqs))]31 for i, freq in enumerate(freqs):32 for mask in range(maxMask):33 if freq >= self._getQuantitySum(quantity, mask):34 validDistribution[i][mask] = True35 return validDistribution36 37 def _getQuantitySum(self, quantity: list[int], mask: int) -> int:38 """Returns the sum of the selected quantity represented by `mask`."""39 return sum(q for i, q in enumerate(quantity) if mask >> i & 1)40