题解 | #24点游戏算法#
24点游戏算法
https://www.nowcoder.com/practice/fbc417f314f745b1978fc751a54ac8cb
#include <math.h> #include <stdbool.h> #include <stdio.h> #include <stdlib.h> const int target =24; const double EPSILON = 1e-6; int solve(double*l,int len) { if(len == 1) { return fabs(l[0]-target) < EPSILON; } int size = len; for(int i=0;i<size;i++) { for(int j=0;j<size;j++) { if(i!=j){ double list2[20]; int len2 = 0; for(int k=0;k<size;k++) { if(k!=i && k!=j) { list2[len2++] = l[k]; } } for(int k=0;k<4;k++) { if(k<2&&i>j) { continue; } if(k==0) { list2[len2++] = l[i]+l[j]; }else if(k==1) { list2[len2++] = l[i]*l[j]; }else if(k==2) { list2[len2++] = l[i] -l[j]; }else if(k==3) { if(fabs(l[j])<EPSILON) continue; list2[len2++] = l[i] / l[j]; } if(solve(list2, len2)) { return true; } len2--; } } } } return false; } int main() { double l[4] = {0}; for(int i=0;i<4;i++) { scanf("%lf %lf %lf %lf",&l[0],&l[1],&l[2],&l[3]); } int flag =0; flag = solve(l,4);; if(flag == 1)printf("true"); else { printf("false"); } }