题解 | #24点游戏算法#

24点游戏算法

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

#include <iostream>
#include <istream>
#include <vector>
using namespace std;

// 简单递归
// 对于每一个数字, 递归遍历加减乘除的情况, 直到剩下最后一个数字, 判断
// 除法的时候需要判断是否能整除
bool isTF(vector<int> nums, int last){
    if(nums.size() == 1){
        if(nums[0] == last){
            return true;
        }else{
            return false;
        }
    }
    bool flag = false;
    for(int i = 0; i < nums.size(); i++){
        vector<int> temp;
        for(int j = 0; j < nums.size(); j++){
            if(i != j){
                temp.push_back(nums.at(j));
            }
            
        }
        int now = nums.at(i);
        
        if(isTF(temp, last + now) || isTF(temp, last - now) || isTF(temp, last * now)){
            flag = true;
        }
        if(last % now == 0){
            if(isTF(temp, last / now)){
                flag = true;
            }
        }
    }
    return flag;

}

int main() {
    int a;
    vector<int> nums;
    while (cin >> a) { // 注意 while 处理多个 case
        nums.push_back(a);
        if(nums.size() == 4){
            cout << boolalpha << isTF(nums, 24) << endl;
            nums.clear();
        }
        
    }
}
// 64 位输出请用 printf("%lld")

全部评论

相关推荐

西松屋:说明原部门有机会把
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务