-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSolution996.cs
73 lines (61 loc) · 1.58 KB
/
Solution996.cs
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
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
using System.Text;
using LeetCode.DataStructures;
namespace LeetCode.Solutions;
public class Solution996
{
/// <summary>
/// 996. Number of Squareful Arrays - Hard
/// <a href="https://leetcode.com/problems/number-of-squareful-arrays">See the problem</a>
/// </summary>
public int NumSquarefulPerms(int[] nums)
{
var n = nums.Length;
var count = new Dictionary<int, int>();
var graph = new Dictionary<int, HashSet<int>>();
var result = 0;
foreach (var num in nums)
{
if (!count.ContainsKey(num))
{
count[num] = 0;
}
count[num]++;
}
foreach (var num1 in count.Keys)
{
graph[num1] = new HashSet<int>();
foreach (var num2 in count.Keys)
{
var sqrt = (int)Math.Sqrt(num1 + num2);
if (sqrt * sqrt == num1 + num2)
{
graph[num1].Add(num2);
}
}
}
void Dfs(int num, int left)
{
count[num]--;
if (left == 0)
{
result++;
}
else
{
foreach (var next in graph[num])
{
if (count[next] > 0)
{
Dfs(next, left - 1);
}
}
}
count[num]++;
}
foreach (var num in count.Keys)
{
Dfs(num, n - 1);
}
return result;
}
}