LeetCode Solutions

996. Number of Squareful Arrays

Time:

Space:

			

class Solution {
 public:
  int numSquarefulPerms(vector<int>& A) {
    int ans = 0;
    sort(begin(A), end(A));
    dfs(A, vector<boool>(A.size()), {}, ans);
    return ans;
  }

 private:
  void dfs(vector<int>& A, vector<bool>&& used, vector<int>&& path, int& ans) {
    if (path.size() > 1 && !isSquare(path.back() + path[path.size() - 2]))
      return;
    if (path.size() == A.size()) {
      ++ans;
      return;
    }

    for (int i = 0; i < A.size(); ++i) {
      if (used[i])
        continue;
      if (i > 0 && A[i] == A[i - 1] && !used[i - 1])
        continue;
      used[i] = true;
      path.push_back(A[i]);
      dfs(A, move(used), move(path), ans);
      path.pop_back();
      used[i] = false;
    }
  }

  bool isSquare(int num) {
    const int root = sqrt(num);
    return root * root == num;
  }
};
			

class Solution {
  public int numSquarefulPerms(int[] A) {
    boolean[] used = new boolean[A.length];
    Arrays.sort(A);
    dfs(A, used, new ArrayList<>());
    return ans;
  }

  private int ans = 0;

  private void dfs(int[] A, boolean[] used, List<Integer> path) {
    if (path.size() > 1 && !isSquare(path.get(path.size() - 1) + path.get(path.size() - 2)))
      return;
    if (path.size() == A.length) {
      ++ans;
      return;
    }

    for (int i = 0; i < A.length; ++i) {
      if (used[i])
        continue;
      if (i > 0 && A[i] == A[i - 1] && !used[i - 1])
        continue;
      used[i] = true;
      path.add(A[i]);
      dfs(A, used, path);
      path.remove(path.size() - 1);
      used[i] = false;
    }
  }

  private boolean isSquare(int num) {
    int root = (int) Math.sqrt(num);
    return root * root == num;
  }
}
			

class Solution:
  def numSquarefulPerms(self, A: List[int]) -> int:
    ans = 0
    used = [False] * len(A)

    def isSquare(num: int) -> bool:
      root = int(sqrt(num))
      return root * root == num

    def dfs(path: List[int]) -> None:
      nonlocal ans
      if len(path) > 1 and not isSquare(path[-1] + path[-2]):
        return
      if len(path) == len(A):
        ans += 1
        return

      for i, a in enumerate(A):
        if used[i]:
          continue
        if i > 0 and A[i] == A[i - 1] and not used[i - 1]:
          continue
        used[i] = True
        dfs(path + [a])
        used[i] = False

    A.sort()
    dfs([])
    return ans