private static final double E = 0.0001;
public boolean judgePoint24(int[] nums) {
if (nums == null || nums.length != 4) {
return false;
}
double[] dnums = new double[4];
for (int i = 0; i < 4; i++) {
dnums[i] = nums[i];
}
return generated24(dnums, 4);
}
private boolean generated24(double[] nums, int n) {
if (n == 1) {
return Math.abs(nums[0] - 24.0) < E;
}
for (int i = 0; i < n - 1; i++) {
double origI = nums[i];
for (int j = i + 1; j < n; j++) {
double origJ = nums[j];
nums[j] = nums[n - 1];
for (double c : getCombinations(origI, origJ)) {
nums[i] = c;
if (generated24(nums, n - 1)) {
return true;
}
}
nums[j] = origJ;
}
nums[i] = origI;
}
return false;
}
private double[] getCombinations(double a, double b) {
return new double[]{ a + b, a - b, b - a, a / b, b / a, a * b};
}
}
在这里插入代码片
发表评论:
◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。