- 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
- 50 lines of Java from the credited upstream file 1994.java.
- The implementation visibly relies on sequence storage, cached states.
- 4 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 int numberOfGoodSubsets(int[] nums) {3 final int[] primes = {2, 3, 5, 7, 11, 13, 17, 19, 23, 29};4 final int n = 1 << primes.length;5 final int maxNum = Arrays.stream(nums).max().getAsInt();6 long[] dp = new long[n];7 int[] count = new int[maxNum + 1];8 9 dp[0] = 1;10 11 for (final int num : nums)12 ++count[num];13 14 for (int num = 2; num <= maxNum; ++num) {15 if (count[num] == 0)16 continue;17 if (num % 4 == 0 || num % 9 == 0 || num % 25 == 0)18 continue;19 final int numPrimesMask = getPrimesMask(num, primes);20 for (int primesMask = 0; primesMask < n; ++primesMask) {21 if ((primesMask & numPrimesMask) > 0)22 continue;23 final int nextPrimesMask = primesMask | numPrimesMask;24 dp[nextPrimesMask] += dp[primesMask] * count[num];25 dp[nextPrimesMask] %= MOD;26 }27 }28 29 return (int) (modPow(2, count[1]) * ((Arrays.stream(dp).sum() - 1) % MOD) % MOD);30 }31 32 private static final int MOD = 1_000_000_007;33 34 private int getPrimesMask(int num, int[] primes) {35 int primesMask = 0;36 for (int i = 0; i < primes.length; ++i)37 if (num % primes[i] == 0)38 primesMask |= 1 << i;39 return primesMask;40 }41 42 private long modPow(long x, long n) {43 if (n == 0)44 return 1;45 if (n % 2 == 1)46 return x * modPow(x, n - 1) % MOD;47 return modPow(x * x % MOD, n / 2);48 }49}50