- 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
- 53 lines of C++ from the credited upstream file 1994.cpp.
- 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:3 int numberOfGoodSubsets(vector<int>& nums) {4 const vector<int> primes{2, 3, 5, 7, 11, 13, 17, 19, 23, 29};5 const int n = 1 << primes.size();6 const int maxNum = ranges::max(nums);7 vector<long> dp(n);8 vector<int> count(maxNum + 1);9 10 dp[0] = 1;11 12 for (const int num : nums)13 ++count[num];14 15 for (int num = 2; num <= maxNum; ++num) {16 if (count[num] == 0)17 continue;18 if (num % 4 == 0 || num % 9 == 0 || num % 25 == 0)19 continue;20 const int numPrimesMask = getPrimesMask(num, primes);21 for (int primesMask = 0; primesMask < n; ++primesMask) {22 if ((primesMask & numPrimesMask) > 0)23 continue;24 const int nextPrimesMask = primesMask | numPrimesMask;25 dp[nextPrimesMask] += dp[primesMask] * count[num];26 dp[nextPrimesMask] %= kMod;27 }28 }29 30 return modPow(2, count[1]) *31 (accumulate(dp.begin() + 1, dp.end(), 0L) % kMod) % kMod;32 }33 34 private:35 static constexpr int kMod = 1'000'000'007;36 37 int getPrimesMask(int num, const vector<int>& primes) {38 int primesMask = 0;39 for (int i = 0; i < primes.size(); ++i)40 if (num % primes[i] == 0)41 primesMask |= 1 << i;42 return primesMask;43 }44 45 long modPow(long x, long n) {46 if (n == 0)47 return 1;48 if (n % 2 == 1)49 return x * modPow(x % kMod, (n - 1)) % kMod;50 return modPow(x * x % kMod, (n / 2)) % kMod;51 }52};53