一个初中小伙伴问的问题,采用暴力+回溯,参考了leetcode的部分题解
#include<iostream>
#include<cmath>
#include<cstring>
#include <sstream>
using namespace std;
double calculate(double x,double y,int opt);
int card[4];
double temp[4];
bool found = false;
void solve(int n);
int point = 0;
string ans[10];
string double2string(double do_b);
int main(){
cout << "请输入四张牌"<<endl;
cin >> card[0] >> card[1] >> card[2] >> card[3];
for(int k = 0; k < 4 ; k ++){
temp[k] = card[k];
}
solve(4);
if(found){
for(int i = 0 ; i < 4 ; i ++){
cout << ans[i] << endl;
}
}else{
cout << "无法计算24" << endl;
}
return 0;
}
void solve(int n){
double backup[4];
if(n == 1){
if(abs(24 - temp[0]) < 1e-6){
found = true;
}
return;
}
for(int i = 0 ; i < n ; i ++){
for(int j = 0; j < n ; j ++){
if(i != j){
for(int opt = 0; opt < 4 ; opt ++){
for(int k = 0; k < 4 ; k ++){
backup[k] = temp[k];
}
temp[i] = calculate(temp[i] , temp[j], opt);
temp[j] = temp[n - 1];
point = point + 1;
solve(n - 1);
if(found) return;
for(int k = 0; k < 4 ; k ++){
temp[k] = backup[k];
}
point = point - 1;
}
}
}
}
}
double calculate(double x,double y,int opt){
switch (opt) {
case 0:
ans[point] = double2string(x) + " + " + double2string(y) + " = " + double2string(x + y);
return x + y;
case 1:
ans[point] = double2string(x) + " - " + double2string(y) + " = " + double2string(x - y);
return x - y;
case 2:
ans[point] = double2string(x) + " * " + double2string(y) + " = " + double2string(x * y);
return x * y;
case 3:
ans[point] = double2string(x) + " / " + double2string(y) + " = " + double2string(x / y);
return x / y;
}
return 0;
}
string double2string(double do_b)
{
string str1;
stringstream sstr;
sstr<<do_b;
sstr>>str1;
return str1;
}