递归——算24

题目:给出4个小于10的正整数,你可以使用加减乘除4种运算以及括号把这4个数连接起来得到一个表达式。现在的问题是,是否存在一种方式使得得到的表达式的结果等于24.

输入:输入数据包括多行,每行给出一组测试数据,包括4个小于10的正整数。最后一组测试数据中包括4个0,表示输入的结束,这组测试不用处理。

输出:对于每一组测试数据,输出一行,如果可以得到24,输出“YES”;否则,输出“NO”。

样例输入

5  5  5  1

1  1  4  2

0  0  0  0

样例输出

YES

NO

 

代码:

#include "stdafx.h"
#include <iostream>
#include <algorithm>
#include <cmath>

using namespace std;

double a[5];
#define EPS 1e-6;

bool isZero(double x)
{
    return fabs(x)<=EPS;
}

bool count24(double a[],int n)
{
    if(n==1)
    {
        if(isZero(a[0]-24))
            return true;
        else
            return false;
    }
    
    double b[5];
    for(int i = 0;i<n-1;++i)
    {
        for(int j = i+1;j<n;++j)
        {
            int m = 0;
            for(int k=0;k<n;++k)
            {
                if(k!=i&&k!=j)
                    b[m++] = a[k];
            }

            b[m] =a[i]+a[j];
            if(count24(b,m+1))
                return true;

            b[m] =a[i]-a[j];
            if(count24(b,m+1))
                return true;

            b[m] =a[j]-a[i];
            if(count24(b,m+1))
                return true;

            b[m] =a[i]*a[j];
            if(count24(b,m+1))
                return true;

            if(!isZero(a[j]))
            {
                b[m] =a[i]/a[j];
                if(count24(b,m+1))
                    return true;
            }

            if(!isZero(a[i]))
            {
                b[m] =a[j]/a[i];
                if(count24(b,m+1))
                    return true;
            }
        }
        return false;
    }
}

int _tmain(int argc, _TCHAR* argv[])
{
    double a[4] = {5,5,5,1};
    bool result = count24(a,sizeof(a)/sizeof(a[0]));
    cout<<(result?"YES":"NO")<<endl;

    return 0;
}

 

转载于:https://www.cnblogs.com/guwei4037/p/8065487.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值