- 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
- 55 lines of C++ from the credited upstream file 3533.cpp.
- The implementation visibly relies on sequence storage, cached states.
- 3 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 vector<int> concatenatedDivisibility(vector<int>& nums, int k) {4 vector<int> lengths;5 vector<int> pows;6 7 ranges::sort(nums);8 9 for (const int num : nums) {10 lengths.push_back(to_string(num).length());11 pows.push_back(static_cast<int>(pow(10, lengths.back())) % k);12 }13 14 vector<vector<int>> mem(1 << nums.size(), vector<int>(k, -1));15 return dp(nums, pows, mem, k, 0, 0) ? reconstruct(nums, pows, mem, k, 0, 0)16 : vector<int>();17 }18 19 private:20 21 22 bool dp(const vector<int>& nums, const vector<int>& pows,23 vector<vector<int>>& mem, int k, int mask, int mod) {24 if (mem[mask][mod] != -1)25 return mem[mask][mod] == 1;26 if (mask == (1 << nums.size()) - 1)27 return mod == 0;28 for (int i = 0; i < nums.size(); ++i)29 if ((mask >> i & 1) == 0) {30 const int newMod = (mod * pows[i] + nums[i]) % k;31 if (dp(nums, pows, mem, k, mask | 1 << i, newMod))32 return mem[mask][mod] = 1;33 }34 return mem[mask][mod] = 0;35 }36 37 38 39 vector<int> reconstruct(const vector<int>& nums, const vector<int>& pows,40 vector<vector<int>>& mem, int k, int mask, int mod) {41 for (int i = 0; i < nums.size(); ++i)42 if ((mask >> i & 1) == 0) {43 const int newMod = (mod * pows[i] + nums[i]) % k;44 if (dp(nums, pows, mem, k, mask | 1 << i, newMod)) {45 vector<int> res{nums[i]};46 vector<int> rest =47 reconstruct(nums, pows, mem, k, mask | 1 << i, newMod);48 ranges::copy(rest, ranges::back_inserter(res));49 return res;50 }51 }52 return {};53 }54};55