题解 | 24点游戏算法 deepseek写的,我没懂

24点游戏算法

https://www.nowcoder.com/practice/fbc417f314f745b1978fc751a54ac8cb

#include <iostream>
#include <vector>
#include <cmath>
#include <algorithm>
using namespace std;

const double EPS = 1e-6;  // 浮点数精度

bool dfs(vector<double>& nums) {
    if(nums.size() == 1) {
        return fabs(nums[0] - 24) < EPS;  // 判断是否等于24
    }
    
    // 尝试所有数字对组合
    for(int i = 0; i < nums.size(); i++) {
        for(int j = 0; j < nums.size(); j++) {
            if(i == j) continue;
            
            vector<double> next;
            // 收集剩余数字
            for(int k = 0; k < nums.size(); k++) {
                if(k != i && k != j) {
                    next.push_back(nums[k]);
                }
            }
            
            // 尝试四种运算
            // 1. 加法
            next.push_back(nums[i] + nums[j]);
            if(dfs(next)) return true;
            next.pop_back();
            
            // 2. 减法
            next.push_back(nums[i] - nums[j]);
            if(dfs(next)) return true;
            next.pop_back();
            
            // 3. 乘法
            next.push_back(nums[i] * nums[j]);
            if(dfs(next)) return true;
            next.pop_back();
            
            // 4. 除法(除数不能为0)
            if(fabs(nums[j]) > EPS) {
                next.push_back(nums[i] / nums[j]);
                if(dfs(next)) return true;
                next.pop_back();
            }
        }
    }
    
    return false;
}

bool judgePoint24(vector<int>& cards) {
    vector<double> nums(4);
    for(int i = 0; i < 4; i++) nums[i] = cards[i];
    
    // 先排序,方便去重(可选)
    sort(nums.begin(), nums.end());
    
    do {
        if(dfs(nums)) return true;
    } while(next_permutation(nums.begin(), nums.end()));
    
    return false;
}

int main() {
    vector<int> cards(4);
    while(cin >> cards[0] >> cards[1] >> cards[2] >> cards[3]) {
        if(judgePoint24(cards)) {
            cout << "true" << endl;
        } else {
            cout << "false" << endl;
        }
    }
    return 0;
}

全部评论

相关推荐

评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务