题解 | #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")

全部评论

相关推荐

06-26 10:08
门头沟学院 C++
北京Golang实习,一个月4700,吃住都不报,公司位置在海淀。请问友友怎么看呢?如果要租房的话有什么建议吗
码农索隆:租房肯定是合租了,剩下的钱,差不多够正常吃饭了,看看能不能学到东西吧
点赞 评论 收藏
分享
不愿透露姓名的神秘牛友
06-26 14:50
人力小鱼姐:有后面墨迹那两句的时间问题早回答完了
点赞 评论 收藏
分享
那一天的Java_J...:他本来公司就是做这个的,不就是正常的游戏客户端和服务器开发,软硬件联动,有啥恶心不恶心的,提前告诉你就是怕你接受不了,接受不了就没必要再往后走流程浪费时间,虽然这公司是一坨。
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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