24点游戏算法
OJ 地址:24点游戏算法
#include <iostream>
#include <algorithm>
using namespace std;
bool ret = false;
void count24(int index, int curRes, int num[])
{
if(curRes == 24)
{
ret = true;
return;
}
if(ret || curRes > 24 || index >= 4)
return;
for(int i = 0; i < 4; i++)
{
switch(i)
{
case 0:
count24(index + 1, curRes + num[index], num);
break;
case 1:
count24(index + 1, curRes - num[index], num);
break;
case 2:
count24(index + 1, curRes * num[index], num);
break;
case 3:
count24(index + 1, curRes / num[index], num);
break;
}
}
}
int main()
{
int num[4];
while(scanf("%d%d%d%d", &num[0], &num[1], &num[2], &num[3]) > 0)
{
sort(num, num + 4);
do{
count24(1, num[0], num);
if(ret)
{
break;
}
}while(next_permutation(num, num + 4));
if(ret)
cout << "true" << endl;
else
cout << "false" << endl;
}
return 0;
}