679. 24 点游戏

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
	}
};
相关推荐
whitelbwwww25 分钟前
cuBLAS--CUDA高性能线性代数计算库--第一部分
c++·线性代数·gpu算力·cuda c++
eggwyw3 小时前
C++设计模式之解释器模式
开发语言·c++
我不会插花弄玉16 小时前
13.多路转接epoll【由浅入深-网络】
网络·c++·epoll
郝学胜-神的一滴18 小时前
Effective STL 条款03:容器中的对象复制要廉价且正确
开发语言·数据结构·c++·算法·rpc·stl
西西弗Sisyphus19 小时前
C++ explicit 关键字工程实践
开发语言·c++
AIgorithmGEEK21 小时前
std::unordered_map 与 std::unordered_set:接口、算法技巧与权衡 (速查)
c++·算法·哈希表·负载因子·桶·unordered_map·unordered_set
一拳一个呆瓜1 天前
【STL】头文件:<cmath>
c++·stl
草莓熊Lotso1 天前
【C++ 基于微服务的即时通讯系统】ElasticSearch 用户数据管理实现
linux·数据库·c++·elasticsearch·微服务·架构
慧都产品智能化1 天前
Qt 开发 CAD/CAM 工序表的隐性成本分析
c++·qt·qt5·qt6.3
eggwyw1 天前
linux下的C\C++多进程多线程编程实例详解
开发语言·c++