679. 24 Game
https://leetcode.com/problems/24-game/description/
/*
* @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);
}
};
Last updated