import java.util.ArrayList;
import java.util.List;
public class Poker24Points {
private static final double EPSILON = 1e-6; // 用于比较浮点数的误差
public static void main(String[] args) {
int[] nums = {1, 2, 3, 4}; // 输入4张牌的数字
List<String> result = calculate24Points(nums);
if (result.isEmpty()) {
System.out.println("无解");
} else {
System.out.println("有解,计算表达式如下:");
for (String expression : result) {
System.out.println(expression);
}
}
}
public static List<String> calculate24Points(int[] nums) {
List<String> result = new ArrayList<>();
double[] arr = new double[nums.length];
for (int i = 0; i < nums.length; i++) {
arr[i] = nums[i];
}
calculate(arr, "", result);
return result;
}
private static void calculate(double[] arr, String expression, List<String> result) {
if (arr.length == 1) {
if (Math.abs(arr[0] - 24) < EPSILON) {
result.add(expression);
}
return;
}
for (int i = 0; i < arr.length; i++) {
for (int j = i + 1; j < arr.length; j++) {
double[] nextArr = new double[arr.length - 1];
int idx = 0;
for (int k = 0; k < arr.length; k++) {
if (k != i && k != j) {
nextArr[idx++] = arr[k];
}
}
// 加法
nextArr[idx] = arr[i] + arr[j];
calculate(nextArr, "(" + expression + "+" + (int) arr[i] + "+" + (int) arr[j] + ")", result);
// 减法
nextArr[idx] = arr[i] - arr[j];
calculate(nextArr, "(" + expression + "+" + (int) arr[i] + "-" + (int) arr[j] + ")", result);
nextArr[idx] = arr[j] - arr[i];
calculate(nextArr, "(" + expression + "+" + (int) arr[j] + "-" + (int) arr[i] + ")", result);
// 乘法
nextArr[idx] = arr[i] * arr[j];
calculate(nextArr, "(" + expression + "+" + (int) arr[i] + "*" + (int) arr[j] + ")", result);
// 除法
if (Math.abs(arr[j]) > EPSILON) {
nextArr[idx] = arr[i] / arr[j];
calculate(nextArr, "(" + expression + "+" + (int) arr[i] + "/" + (int) arr[j] + ")", result);
}
if (Math.abs(arr[i]) > EPSILON) {
nextArr[idx] = arr[j] / arr[i];
calculate(nextArr, "(" + expression + "+" + (int) arr[j] + "/" + (int) arr[i] + ")", result);
}
}
}
}
}