- 提一句:四则运算里面答案中案例里没有除法
- 数字需要排序,算数符号也需要排序
- 总的题来说就是递归两个东西,一个是数字的全排列,一个是算数符号的全排列
- 代码见如下(本人弱鸡,勿喷)
import java.util.*;
public class Main {
static int[] array;
static boolean[] vis;
static int n;
static char[] operators = new char[]{'*', '+', '-'};
static ArrayList<String> ansStr = new ArrayList<>();
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
n = sc.nextInt();
array = new int[n];
vis = new boolean[n];
for (int i = 0; i < n; i++) {
array[i] = sc.nextInt();
}
Arrays.sort(array);
for (int i = 0; i < n; i++) {
vis[i] = true;
StringBuffer operate = new StringBuffer();
operate.append(array[i]);
if (dfs(operate, 1)) {
break;
}
vis[i] = false;
}
if (ansStr.size() == 0) {
System.out.println("NO");
} else {
System.out.println("YES");
String ans = ansStr.get(0);
int size = ansStr.size();
for (int i = 1; i < size; i++) {
if (ans.compareTo(ansStr.get(i)) > 0) {
ans = ansStr.get(i);
}
}
System.out.println(ans);
}
}
public static boolean dfs(StringBuffer operate, int floor) {
if (floor == array.length) {
if (isTwentyFour(operate.toString())) {
ansStr.add(operate.append("=24").toString());
return true;
}
return false;
}
for (int i = 0; i < n; i++) {
if (!vis[i]) {
vis[i] = true;
for (char operator : operators) {
if (cal(new StringBuffer(operate), operator, i, floor)) {
return true;
}
}
vis[i] = false;
}
}
return false;
}
static public boolean cal(StringBuffer operate, char operator, int numIdx, int floor) {
operate.append(operator);
operate.append(array[numIdx]);
return dfs(operate, floor + 1);
}
public static boolean isTwentyFour(String s) {
char[] chs = s.toCharArray();
double preNum = 0;
Stack<Double> nums = new Stack<>();
Stack<Character> operators = new Stack<>();
for (int i = 0; i < chs.length; i++) {
if (chs[i] >= '0' && chs[i] <= '9') {
preNum = preNum * 10 + chs[i] - '0';
} else {
if (preNum != 0) {
nums.push(preNum);
}
preNum = 0;
operators.push(chs[i]);
if (chs[i] == '*' || chs[i] == '/') {
i++;
while (i < chs.length && chs[i] >= '0' && chs[i] <= '9') {
preNum = preNum * 10 + chs[i] - '0';
i++;
}
i--;
nums.push(calculate(nums.pop(), preNum, operators.pop()));
}
preNum = 0;
}
}
if (preNum != 0) {
nums.push(preNum);
}
LinkedList<Double> numsReverse = new LinkedList<>();
LinkedList<Character> operatorsReverse = new LinkedList<>();
while (!nums.isEmpty()){
numsReverse.addFirst(nums.pop());
}
while (!operators.isEmpty()){
operatorsReverse.addFirst(operators.pop());
}
int size = operatorsReverse.size();
for (int i = 0; i < size; i++) {
char operator = operatorsReverse.get(i);
double a = numsReverse.get(i);
double b = numsReverse.get(i + 1);
numsReverse.set(i + 1,calculate(a,b,operator));
}
return numsReverse.get(size) == 24;
}
public static double calculate(double a, double b, char operator) {
switch (operator) {
case '+':
return a + b;
case '-':
return a - b;
case '*':
return a * b;
case '/':
if (a % b != 0) {
return Double.MIN_VALUE;
}
return a / b;
}
return 0;
}
}