> For the complete documentation index, see [llms.txt](https://hao-fu-1.gitbook.io/oj/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://hao-fu-1.gitbook.io/oj/exhaustive-search/yun-suan/679.-24-game.md).

# 679. 24 Game

https\://leetcode.com/problems/24-game/description/

四个数，问任意顺序下插入+-\*/()后能否最后让expression的结果等于24。和evaluate division类似，遍历所有的可能，有24就返回。因为允许括号，所以这里精度要求是double，因为double计算结果即使是0的可能也因为精度误差得不到0，所以用预设的误差eps范围，当和0差距在eps以内就算是0。DFS时每次选出两个元素，遍历各种它俩的运算可能结果并放到path里。

代码参考了[这](https://link.zhihu.com/?target=https%3A//www.cnblogs.com/grandyang/p/8395062.html)。

```cpp
/*
 * @lc app=leetcode id=679 lang=cpp
 *
 * [679] 24 Game
 */
class Solution {
public:
    bool dfs(vector<double> &path, const double eps) {
        if (path.size() == 1) {
            if (abs(path[0] - 24) < eps) return true;
            return false;
        }
        for (int i = 0; i < path.size(); ++i) {
            for (int j = 0; j < i; ++j) {
                double p = path[i], q = path[j];
                vector<double> t{p + q, p - q, q - p, p * q};
                if (p > eps) t.push_back(q / p);
                if (q > eps) t.push_back(p / q);
                path.erase(path.begin() + i);
                path.erase(path.begin() + j);
                for (const auto d : t) {
                    path.push_back(d);
                    if (dfs(path, eps)) return true;
                    path.pop_back();
                }
                path.insert(path.begin() + j, q);
                path.insert(path.begin() + i, p);
            }
        }
        return false;
    }
    bool judgePoint24(vector<int>& nums) {
        double eps = 0.001;
        vector<double> path(nums.begin(), nums.end());
        return dfs(path, eps);
    }
};


```
