class Solution {
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};
}
}
leetcode 679 24 Game
最新推荐文章于 2020-08-24 15:19:22 发布