题解 | #24点运算#
24点运算
https://www.nowcoder.com/practice/7e124483271e4c979a82eb2956544f9d
不懂算法,就是瞎做,按着数学的思想,把思路变成代码,等刷完题再好好学学算法,整点高大上的名词
import java.util.*;
// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
private static String[] opt = new String[]{"","",""};
private static HashMap<String,String> sMaps = new HashMap<>();
private static List<String> sResults = new ArrayList<>();
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
String[] lines = s.nextLine().trim().split(" ");
for (int i =0;i<lines.length;i++){
if (lines[i].equalsIgnoreCase("J")){
lines[i] = "11";
sMaps.put(lines[i],"J");
}else if (lines[i].equalsIgnoreCase("Q")){
lines[i]="12";
sMaps.put(lines[i],"Q");
}else if (lines[i].equalsIgnoreCase("K")){
lines[i]="13";
sMaps.put(lines[i],"K");
}else if (lines[i].equalsIgnoreCase("A")){
lines[i]="1";
sMaps.put(lines[i],"A");
}else{
sMaps.put(lines[i],lines[i]);
}
if (lines[i].equalsIgnoreCase("joker")){
System.out.println("ERROR");
return;
}
}
int a = Integer.parseInt(lines[0]);
int b = Integer.parseInt(lines[1]);
int c = Integer.parseInt(lines[2]);
int d = Integer.parseInt(lines[3]);
int[] ints = new int[]{a, b, c, d};
List<int[]> data = new ArrayList<>();
//输出所有 a b c d可能的排列组合
//先从0位置取数,可以取4种,依次类推
for (int i =0;i<4;i++){
int[] tmp = new int[4];
tmp[0]=ints[i];
for (int j =0;j<3;j++){
int[] tmp1 = removeElements(ints,tmp[0]);
tmp[1]=tmp1[j];
for (int k=0;k<2;k++){
int[] tmp2 = removeElements(tmp1,tmp[1]);
tmp[2]=tmp2[k];
for (int l=0;l<1;l++){
int[] tmp3 =removeElements(tmp2,tmp[2]);
tmp[3]=tmp3[l];
int[] temp = new int[4];
temp[0]=tmp[0];
temp[1]=tmp[1];
temp[2]=tmp[2];
temp[3]=tmp[3];
data.add(temp);
}
}
}
}
for (int[] tmp : data){
cal(tmp[0],tmp,1);
}
if (sResults.isEmpty()){
System.out.println("NONE");
}else{
System.out.println(sResults.get(0));
}
}
private static int[] removeElements(int[] arr,int value){
int[] ints = new int[arr.length-1];
int i=0;
boolean first=true;//第一个遇到的删除,其他的应添加到队列里
for (int tmp : arr){
if (value!=tmp){
ints[i]=tmp;
i++;
}else{
if (first){
first=false;
}else{
ints[i]=tmp;
i++;
}
}
}
return ints;
}
public static int count=0;
private static int cal(int result,int[] ints,int index){
if (index>=4){
count++;
if (result==24){
String res ="" +getMappingString(ints[0]) +opt[0]
+getMappingString(ints[1])+opt[1]
+getMappingString(ints[2])+opt[2]
+getMappingString(ints[3]);
sResults.add(res);
}
return result;
}
// System.out.println("执行加法:"+result+",index="+index);
int add = result + ints[index];
opt[index-1]="+";
cal(add,ints,index+1);
int subtract =result - ints[index];
opt[index-1]="-";
cal(subtract,ints,index+1);
// System.out.println("执行减法:"+result+",index="+index);
int times = result * ints[index];
opt[index-1]="*";
cal(times,ints,index+1);
// System.out.println("执行乘法:"+result+",index="+index);
int division =result / ints[index];
opt[index-1]="/";
return cal(division,ints,index+1);
}
private static String getMappingString(int value){
return sMaps.get(value+"");
}
}