题解 | #24点游戏算法#
24点游戏算法
https://www.nowcoder.com/practice/fbc417f314f745b1978fc751a54ac8cb
#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;
bool check(vector<double>& nums, double result){
if (nums.empty()) {
return result == 24;
}
for(int i = 0; i < nums.size(); i++) { //遍历三个位置的所有可能运算符
vector<double> res(nums);
res.erase(res.begin() + i);
if (check(res, result + nums[i])
|| check(res, result - nums[i])
|| check(res, result * nums[i])
|| check(res, result / nums[i]))
return true;
}
return false;
}
int main(){
vector<double> nums(4);
while(cin >> nums[0] >> nums[1] >> nums[2] >> nums[3]){ //输入4个数字
if (check(nums, 0)) {
cout << "true" << endl;
} else {
cout << "false" << endl;
}
}
return 0;
}
#include<vector>
#include<algorithm>
using namespace std;
bool check(vector<double>& nums, double result){
if (nums.empty()) {
return result == 24;
}
for(int i = 0; i < nums.size(); i++) { //遍历三个位置的所有可能运算符
vector<double> res(nums);
res.erase(res.begin() + i);
if (check(res, result + nums[i])
|| check(res, result - nums[i])
|| check(res, result * nums[i])
|| check(res, result / nums[i]))
return true;
}
return false;
}
int main(){
vector<double> nums(4);
while(cin >> nums[0] >> nums[1] >> nums[2] >> nums[3]){ //输入4个数字
if (check(nums, 0)) {
cout << "true" << endl;
} else {
cout << "false" << endl;
}
}
return 0;
}