996. Number of Squareful Arrays

📋 Đề Bài

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].

 

Example 1:

Input: nums = [1,17,8]
Output: 2
Explanation: [1,8,17] and [17,8,1] are the valid permutations.

Example 2:

Input: nums = [2,2,2]
Output: 1

 

Constraints:

  • 1 <= nums.length <= 12
  • 0 <= nums[i] <= 109

🧠 Thuật Toán & Kỹ Thuật

DFS (Tìm kiếm theo chiều sâu)Hash Table (Bảng băm)
⏱️ Thời gian O(V+E)
💾 Không gian O(V)

💻 Lời Giải

C++ 0996-number-of-squareful-arrays.cpp
class Solution {
private:
    vector<int> nums, path;
    unordered_map<int, int> cnt;
    int n, ans;
    
public:
    bool checkSquare(int num) {
        int s = sqrt(num);
        return num == s*s;
    }
    
    void dfs(int prev) {
        if (path.size() == n) {
            ans++;
            return;
        }
        for (auto &[key, _] : cnt) {
            if (cnt[key] > 0) {
                if (prev == -1 or checkSquare(prev + key)) {
                    cnt[key]--;
                    path.push_back(key);
                    dfs(key);
                    cnt[key]++;
                    path.pop_back();
                }
            }
        }
    }
    
    int numSquarefulPerms(vector<int>& nums) {
        n = nums.size(), ans = 0;
        this->nums = nums;
        for (int num : nums) {
            cnt[num]++;
        }
        dfs(-1);
        return ans;
    }
};