996. Number of Squareful Arrays
An array is squareful if the sum of every pair of adjacent elements is a perfect square.
Given an integer array nums, return the number of permutations of nums that are squareful.
Two permutations perm1 and perm2 are different if there is some index i such that perm1[i] != perm2[i].
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36
| class Solution { unordered_map<int, int> counter; unordered_map<int, vector<int>> ref; int backTracking(int n, int pick) { if(!pick) return 1; int res = 0; for(auto r : ref[n]) { if(counter[r]) { counter[r]--; res += backTracking(r, pick - 1); counter[r]++; } } return res; } public: int numSquarefulPerms(vector<int>& nums) { for(auto n : nums) counter[n]++; for(auto [i, _] : counter) { for(auto [j, _]: counter) { int sum = i + j, sq = sqrt(i + j); if(sum == sq * sq) { ref[i].push_back(j); } } } int res = 0; for(auto [n, _]: counter) { counter[n]--; res += backTracking(n, nums.size() - 1); counter[n]++; } return res; } };
|