题解 | #24点游戏算法#

24点游戏算法

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

经典全排列变种体,在找全排列的时候可以在每个节点多dfs几次把运算的可能顺序的结果也得到,注意整数除法可能取0的情况

#include <iostream>

using namespace std;

const int N = 10;

int n = 4, g[N];
bool st[N], is24;
string s[N * N * N * N];

void dfs(int u, double res) {
    
    if (u == n) {
        if (res == 24) is24 = true;
    }
    
    for (int i = 1; i <= n; i ++) {
        if (!st[i]) {
            st[i] = true;
            dfs(u + 1, res + g[i]);
            dfs(u + 1, res - g[i]);
            dfs(u + 1, res * g[i]);
            dfs(u + 1, res / g[i]);
            st[i] = false;
        }
    }
}

int main() {
    for (int i = 1; i <= n; i ++) {
        cin >> g[i];
    }
    dfs(0, 0);
    if (is24) cout << "true" << endl;
    else cout << "false" << endl;
    
    
}
全部评论
这种写法,没有考虑括号优先级的情况吧?
点赞 回复 分享
发布于 2022-09-02 17:38 北京
用例7 2 1 10答案错误了诶
点赞 回复 分享
发布于 2022-08-08 01:16

相关推荐

qq乃乃好喝到咩噗茶:院校后面加上211标签,放大加粗,招呼语也写上211
点赞 评论 收藏
分享
每晚夜里独自颤抖:要求太多的没必要理
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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