679. 24 点游戏
题目链接:679. 24 点游戏
代码如下:
cpp
//参考链接:https://leetcode.cn/problems/24-game/solutions/3756006/mei-ci-he-bing-liang-zhang-pai-di-gui-xi-0sdu
class Solution {
public:
bool judgePoint24(vector<int>& cards) {
vector<double> a(cards.begin(),cards.end());
return dfs(a);
}
private:
const double EPS = 1e-9;
bool dfs(vector<double>& cards) {
int n = cards.size();
if (n == 1) {
return abs(cards[0] - 24) < EPS; // 如果只剩一个数,判断是否接近 24
}
//选两张牌 x=cartds[i]和y=cards[j],进行四则运算
for (int i = 0;i < n;i++) {
double x = cards[i];
for (int j = i + 1;j < n;j++) {
double y = cards[j];
//六种情况:加减乘除,其中减和除都有两种不同的顺序
vector<double> candidates = { x + y,x - y,y - x,x * y };
if (abs(y) > EPS) {
candidates.push_back(x / y);
}
if (abs(x) > EPS) {
candidates.push_back(y / x);
}
auto new_cards = cards;
new_cards.erase(new_cards.begin() + j); // 移除第 j 张牌
for (double res : candidates) {
new_cards[i] = res; // 将结果放在第 i 张牌的位置
if (dfs(new_cards)) {
return true;
}
}
}
}
return false; // 如果没有找到满足条件的组合,返回 false
}
};