递归算24

有关于算24的问题
通过递归来实现
递归的思考步骤
第一步:分解成小规模的问题
第二步:找出边界的条件

#include<bits/stdc++.h>
using namespace std;
double a[5];
#define eps 1e-6
const int num=10;
bool IsZero(double x) { //double浮点数除法要用精度判断
	if(abs(x<=eps)) return true;
	else return false;
}
bool Count(double a[],int n) {
	if(n==1) {//只有一个数的情况
		if(IsZero(a[0])) {
			return true;
		}
		return false;
	}
	double b[5];
	for(int i=0; i<n; i++) { //分解成子问题两两相加缩小一个规模
		for(int j=i+1; j<n; j++) { //枚举两个数的组合
			int m=0;//剩下的数字
			for(int k=0; k<n; k++) {
				if(k!=i&&k!=j)//选出的数为ij
					b[m++]=a[k];
			}
			//枚举两数所有情况
			b[m]=a[i]+a[j];//将第一对情况加入b中
			if(Count(b,m+1))//m本身为n-2个数字,现在数组中应该剩下n-1,也即规模减小1
				return true;
			b[m]=a[i]-a[j];
			if(Count(b,m+1))
				return true;
			b[m]=a[j]-a[i];
			if(Count(b,m+1))
				return true;
			b[m]=a[i]*a[j];
			if(Count(b,m+1))
				return true;
			if(Count(b,m+1))
				return true;
			if(!IsZero(a[j])) { //除数不为0
				b[m]=a[i]/a[j];
				if(Count(b,m+1))
					return true;
			}
			if(!IsZero(a[i])) { //除数不为0
				b[m]=a[j]/a[i];
				if(Count(b,m+1))
					return true;
			}
		}
		return false;
	}
}
int main() {
	for(int i=0; i<4; i++)
		cin>>a[i];
	int x;
	for(x=0; x<4; x++) {
		if(a[x]==0)
			continue;
		else break;
	}
	if(x==4) return 0;
	if(Count(a,4))
		cout<<"YES"<<endl;
	else
		cout<<"NO"<<endl;
	return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值