class SL
{
public bool JudgePoint24(int[] nums)
{
List list = new List();
foreach (int i in nums) list.Add((double)i); //为dfs做准备
return dfs(list);
}
private bool dfs(List list)
{
if (list.Count == 1)
{//一个数时判断相等
if (Math.Abs(list[0] - 24.0) < 0.001) return true; //考虑除法造成的小数点
return false;
}
for (int i = 0; i < list.Count; ++i)
{
for (int j = i + 1; j < list.Count; ++j)
{
foreach (double c in generatePossibleResults(list[i], list[j]))
{
List nextRound = new List();
nextRound.Add(c); //遍历两个数的所有可能性
for (int k = 0; k < list.Count; ++k)
{ //添加剩余项到next round
if (k == i || k == j) continue;
nextRound.Add(list[k]);
}
if (dfs(nextRound)) return true;
}
}
}
return false;
}
//生成两个数所有的组合
private List generatePossibleResults(double a, double b)
{
List res = new List();
res.Add(a + b);
res.Add(a - b);
res.Add(b - a);
res.Add(a * b);
res.Add(a / b);
res.Add(b / a);
return res;
}
}

C#改JAVA

class Solution
{
public boolean judgePoint24(int[] nums)
{
ArrayList list = new ArrayList<>();
for (int n:nums)
{
list.add((double)n);
}
return Prm(list);
}
public boolean Prm(ArrayList list)
{
if (list.size() == 1)
{
return Math.abs(list.get(0) - 24) < 1e-6;
}
for (int i = 0; i < list.size(); i++)
{
for (int j = i + 1; j < list.size(); j++)
{
for (double k:AllTowRes(list.get(i), list.get(j)))
{
ArrayList nextRound = new ArrayList<>();
nextRound.add(k);
for (int v = 0; v < list.size(); v++)
{
if (v == i || v == j) continue;
nextRound.add(list.get(v));
}
if (Prm(nextRound)) return true;
}
}
}
return false;
}
public ArrayList AllTowRes(double a, double b)
{
ArrayList res = new ArrayList<>();
res.add(a + b);
res.add(a - b);
res.add(b - a);
if (b != 0) res.add(a / b);
if (a != 0) res.add(b / a);
return res;
}
}