- 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
- 54 lines of Java from the credited upstream file 1655.java.
- The implementation visibly relies on sequence storage, hash lookup, ordered lookup, cached states.
- 7 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 public boolean canDistribute(int[] nums, int[] quantity) {3 List<Integer> freqs = getFreqs(nums);4 5 6 boolean[][] validDistribution = getValidDistribution(freqs, quantity);7 final int n = freqs.size();8 final int m = quantity.length;9 final int maxMask = 1 << m;10 11 12 boolean[][] dp = new boolean[n + 1][maxMask];13 dp[n][maxMask - 1] = true;14 15 for (int i = n - 1; i >= 0; --i)16 for (int mask = 0; mask < maxMask; ++mask) {17 dp[i][mask] = dp[i + 1][mask];18 final int availableMask = ~mask & (maxMask - 1);19 for (int submask = availableMask; submask > 0; submask = (submask - 1) & availableMask)20 if (validDistribution[i][submask])21 dp[i][mask] = dp[i][mask] || dp[i + 1][mask | submask];22 }23 24 return dp[0][0];25 }26 27 private List<Integer> getFreqs(int[] nums) {28 List<Integer> freqs = new ArrayList<>();29 Map<Integer, Integer> count = new HashMap<>();30 for (final int num : nums)31 count.merge(num, 1, Integer::sum);32 return new ArrayList<>(count.values());33 }34 35 boolean[][] getValidDistribution(List<Integer> freqs, int[] quantity) {36 final int maxMask = 1 << quantity.length;37 boolean[][] validDistribution = new boolean[freqs.size()][maxMask];38 for (int i = 0; i < freqs.size(); ++i)39 for (int mask = 0; mask < maxMask; ++mask)40 if (freqs.get(i) >= getQuantitySum(quantity, mask))41 validDistribution[i][mask] = true;42 return validDistribution;43 }44 45 46 int getQuantitySum(int[] quantity, int mask) {47 int sum = 0;48 for (int i = 0; i < quantity.length; ++i)49 if ((mask >> i & 1) == 1)50 sum += quantity[i];51 return sum;52 }53}54