回溯算法:计算24点牌

本文介绍了如何运用回溯算法解决24点游戏。通过将4个整数放入数组,计算不同数字组合与运算符的排列,递归地进行计算并更新数组,直到数组中只剩下一个数字,从而找出所有可能的解决方案。

回溯算法:计算24点牌

在这里插入图片描述
1.将4个整数放入数组中
2.在数组中取两个数字的排列,共有 P(4,2) 种排列。对每一个排列,对 – * / 每一个运算符,
3.根据此排列的两个数字和运算符,计算结果
4.改表数组:将此排列的两个数字从数组中去除掉,将 2.1.1 计算的结果放入数组中
5.对新的数组,重复步骤 2
恢复数组:将此排列的两个数字加入数组中,将 2.1.1 计算的结果从数组中去除掉可见这是一个递归过程。步骤 2 就是递归函数。当数组中只剩下一个数字的时候,这就是表达式的最终结果,此时递归结束。

#include<iostream>
#include<string>
#include<vector>
#include<algorithm>
using namespace std;
bool isFind = false;
int sum = 0;
void find(vector<double> &nums, int n)
{
	//构造数组,因为回溯后加起来的数字减不回去
	vector<double> tmp(nums.begin(), nums.begin() + n);
	//退出条件
	if (n == 1)
	{
		
		if (tmp[0] == 24)
		{
			isFind = true;
			return;
		}
	}
	//单层节点
	for (int i = 0; i < n; i++)
	{
		for (int j = i + 1; j < n; j++)
		{
			double a = tmp[i];
			double b = tmp[j];
			tmp[j] = tmp[n - 1];
			tmp[i] = a + b;
			find(tmp, n - 1);
			tmp[i] = a - b;
			find(tmp, n - 1);
			tmp[i] = b - a;
			find(tmp, n - 1);
			tmp[i] = a * b;
			find(tmp, n - 1);
			if (b != 0)
			{
				tmp[i] = a / b;
				find(tmp, n - 1);
			}
			if (a != 0)
			{
				tmp[i] = b / a;
				find(tmp, n - 1);
			}
			//回溯
			tmp[i] = a;
			tmp[j] = b;
		}
	}
}
int main()
{
	int n1, n2, n3, n4;
	while (cin >> n1 >> n2 >> n3 >> n4)
	{
		vector<double> nums(4, 0);//注意用double
		nums[0] = n1;
		nums[1] = n2;
		nums[2] = n3;
		nums[3] = n4;
		find(nums, 4);
		if (isFind)
			cout << "true" << endl;
		else
			cout << "false" << endl;
		isFind = false;
	}
	return 0;
	
}
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值