- Translate each rule into one explicit state update.
- Maintain the invariant after every processed item.
- Return the accumulated state once all relevant input has been handled.
Code notes
- 53 lines of C++ from the credited upstream file 2572.cpp.
- The implementation visibly relies on sequence storage.
- 3 loop blocks detected.
Complexity
Count the number and nesting of passes over the input, then include the maintained containers in the memory estimate.
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 squareFreeSubsets(vector<int>& nums) {4 vector<vector<int>> mem(nums.size(),5 vector<int>(1 << (kPrimesCount + 1), -1));6 vector<int> masks;7 8 for (const int num : nums)9 masks.push_back(getMask(num));10 11 12 13 return (squareFreeSubsets(masks, 0, 1, mem) - 1 + kMod) % kMod;14 }15 16 private:17 static constexpr int kMod = 1'000'000'007;18 static constexpr int kPrimesCount = 10;19 static constexpr int primes[] = {2, 3, 5, 7, 11, 13, 17, 19, 23, 29};20 21 int squareFreeSubsets(const vector<int>& masks, int i, int used,22 vector<vector<int>>& mem) {23 if (i == masks.size())24 return 1;25 if (mem[i][used] != -1)26 return mem[i][used];27 const int pick = (masks[i] & used) == 028 ? squareFreeSubsets(masks, i + 1, used | masks[i], mem)29 : 0;30 const int skip = squareFreeSubsets(masks, i + 1, used, mem);31 return mem[i][used] = (pick + skip) % kMod;32 }33 34 35 36 37 int getMask(int num) {38 int mask = 0;39 for (int i = 0; i < sizeof(primes) / sizeof(int); ++i) {40 int rootCount = 0;41 while (num % primes[i] == 0) {42 num /= primes[i];43 ++rootCount;44 }45 if (rootCount >= 2)46 return -1;47 if (rootCount == 1)48 mask |= 1 << i;49 }50 return mask << 1;51 }52};53