题解 | #24点游戏算法#
24点游戏算法
https://www.nowcoder.com/practice/fbc417f314f745b1978fc751a54ac8cb
#include <stdio.h> #include <stdlib.h> #include <string.h> double num[4]; int vis[4]; int dfs(int step,double sum) { if(step == 3 && sum == 24) { return 1; }else { step++; for(int i=0;i<4;i++) { if(vis[i]==0){ vis[i]=1; if(dfs(step,sum+num[i])|| dfs(step,sum-num[i])|| dfs(step,sum*num[i])|| dfs(step,sum/num[i])) { return 1; } vis[i]=0; } } } return 0; } int main() { scanf("%lf %lf %lf %lf",&num[0],&num[1],&num[2],&num[3]); memset(vis,0,sizeof(vis)); if(dfs(-1,0)) { printf("true\n"); }else { printf("false\n"); } }