0
点赞
收藏
分享

微信扫一扫

(二) 递归 + (三)枚举 2787 算24


2787 算24

  • ​​AC代码​​
  • ​​解析​​
  • ​​其实主要是递归式和边界条件的寻找​​
  • ​​找变化的量​​
  • ​​分析变量的变化​​
  • ​​坑​​
  • ​​abs()和fabs()​​
  • ​​bool函数的判断返回一定要确定​​
  • ​​新知识​​
  • ​​true false​​
  • ​​浮点数的比较​​
  • ​​快速的判断方法​​

AC代码

/**********************************************************************/
/* _ _ __ __ ____ _____ */
/* | | | | | \/ | / ___| | ___| */
/* | | | | | |\/| | | | | |___ */
/* | |_| | | | | | | |___ | |___| */
/* \___/ |_| |_| \____| |_| */
/**********************************************************************/
#include <iostream>
#include <cmath>

using namespace std;
double number[4] = {0};
#define

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

bool count(double number[] , int n)
{
if(n == 1)
{
if(isZero(number[0] - 24))
{
return true;
}
else
{
return false;
}
}
for(int i =0;i < n-1;i++)
{
for(int j = i+1;j <n;j++ )
{
double exnum[4] = {0};
int m = 0;
for(int k = 0;k<n;k++)
{
if(k != i && k!= j)
{
exnum[m++] = number[k];
}
}
exnum [m] = number[i] + number[j];
if(count(exnum,m+1))
{
return true;
}
exnum [m] = number[i] - number[j];
if(count(exnum,m+1))
{
return true;
}
exnum [m] = number[j] - number[i];
if(count(exnum,m+1))
{
return true;
}
exnum [m] = number[i] * number[j];
if(count(exnum,m+1))
{
return true;
}
if(number[i] != 0)
{
exnum [m] = number[j] / number[i];
if(count(exnum,m+1))
{
return true;
}
}
if(number[j] != 0)
{
exnum [m] = number[i] / number[j];
if(count(exnum,m+1))
{
return true;
}
}

}
}
return false;

}

int main()
{

while(true)
{
for(int i =0;i<4;i++)
{
cin >> number[i];
}
if(isZero(number[0]) == true && isZero(number[1]) == true && isZero(number[2]) == true && isZero(number[3]) == true )
{
break;
}
if(count(number, 4))
{
cout << "YES" << endl;
}
else
{
cout << "NO" << endl;
}

}

return 0;
}

解析

​​参看中国大学慕课郭炜老师课程讲解递归二​​​ 函数调用自己,递归
多重for循环遍历
当m<n时,一定会空出n-m个盘子,所以

m>=n时,有空盘子的情况和将m苹果放满n-1盘子里是一样的,这里递归一下
没有空盘子的情况,和先每个盘子放一个苹果,再往剩下n个盘子里放m-n苹果

其实主要是递归式和边界条件的寻找

分为两步

找变化的量

分析变量的变化

边界条件为什么是

if(m == 0)
{
return 1;
}
if(n <= 0)
{
return 0;
}

因为

return apple(m,n-1)+apple(m-n,n);

中,n不断变化,每次减一 m不断变化,每次m-n
m-n只可能>=0,因为每次一进入,进行了筛选,所以考虑 m==0
n最终也会减到0

abs()和fabs()

浮点数使用fabs(),在cmath.h
整型使用abs(),stdio.h

bool函数的判断返回一定要确定

if(isZero(number[0] - 24))
{
return true;
}
else//第一次写忘记了返回false 不过在整个count函数后面有false命令
{
return false;
}

新知识

true false

用true和false而不是1和0
当我们把一个非布尔类型的算术值赋给布尔类型时,初始值为0则结果为false,否则结果为true(不为0即真)。
当我们把一个布尔值赋给非布尔类型时,初始值为false则结果为0,初始值为true则结果为1。

浮点数的比较

浮点数比较是否相等,不能用 ==
利用和某一个数差值是否小于 1e-6来判断是否为该数

#define

bool isZero(double i)
{
// if( fabs(i) < EPS)
// {
// return 1;//true
// }
// else
// {
// return 0;//false
// }
return fabs(i) < EPS;
}

而且不用进行多余的判断,直接返回判断的表达式即可

快速的判断方法

return  fabs(i) < EPS;
if(number[i] != 0)

进行0,1的判断,不用== 以及!=,直接对值进行判断
改成

if(!number[i])


举报

相关推荐

0 条评论