t1:表达式计算
思路:
要知道表达式是个递归的定义,如图
因此就可以对表达式进行递归分析处理。
代码如下:
#include <iostream>
#include <cstring>
#include <cstdlib>
using namespace std;
int factor_value();//表达式=若干个项的加减,项=若干个因子的乘除,因子=整数或(表达式)
int term_value(); //故是一个递归
int expression_value();
int main() {
cout << expression_value() << endl;
return 0;
}
int expression_value()//求一个表达式的值
{
int result = term_value();//求第一项的值
bool more = true;
while (more)
{
char op = cin.peek(); //看一个字符,不取走
if (op == '+' || op == '-') {
cin.get(); //从输入中取走一个字符
int value = term_value();
if (op == '+') result += value;
else result -= value;
}
else more = false;
}
return result;
}
int term_value()//求一个项的值
{
int result = factor_value();//求第一个因子的值
while (true) {
char op = cin.peek();
if (op == '*' || op == '/') {
cin.get();
int value = factor_value();
if (op == '*')
result *= value;
else result /= value;
}
else
break;
}
return result;
}
int factor_value()//求一个因子的值
{
int result = 0;
char c = cin.peek();
if (c == '(') {
cin.get();
result = expression_value();
cin.get();
}
else {
while (isdigit(c)) {
result = 10 * result + c - '0';
cin.get();
c = cin.peek();
}
}
return result;
}
t2:上台阶
思路:
台阶的走法只有两种,要么一次上一阶,要么上两阶,故可得表达式然后就要判断的就是递归结束的边界条件,也就是当n<0时直接结束,当n=0时返回1。
代码如下:
#include <iostream>
using namespace std;
int N;
int stairs(int n);
int stairs(int n)
{
if (n < 0)
return 0;
if (n == 0)
return 1;
return stairs(n - 1) + stairs(n - 2);
}
int main()
{
while (cin >> N) {
cout << stairs(N) << endl;
}
return 0;
}
t3:放苹果
思路:
终止条件就是当盘子和苹果数都为零
代码如下:
#include <iostream>
using namespace std;
int f(int m, int n) {
if (n > m) //盘子数目大于苹果数目
return f(m, m);//多出来的盘子不会影响摆放方法,因此将盘子数目和苹果数目变为相同
if (m == 0) //苹果数目为零
return 1;//返回值为1,也就是所有盘子都不放苹果
if (n == 0)//盘子数目为零
return 0;//无盘子放则返回零
return f(m, n - 1) + f(m - n, n);
}
int main() {
int t, m, n;
cin >> t;
while (t--) {
cin >> m >> n;
cout << f(m, n) << endl;
}
return 0;
}
t4:算24
思路:
代码如下:
#include <iostream>
#include <cmath>
#define e 1e-6
using namespace std;
//题目是把4个数进行运算
//我们把问题简化一下 变成第一次两个算 第二次n-2个数算 这n-2个数又选两个算......
//直到算到剩下1个数的时候 这一个数也就是答案了
//把问题化成多个小问题 直到不能再化为止
bool dfs(double a[], int n)
{
if (n == 1)
{
if (fabs(a[0] - 24) <= e) //浮点数的等价比价
return true;
else
return false;
}
double b[5];
//把这个没算的数放b数组里 (这次两个数的结果也放b里) 相当于b的个数是n-1
for (int i = 0; i < n - 1; i++)
{
for (int j = i + 1; j < n; j++)
//两成for循环 找出所有的两个数的组合
{
int m = 0; //表示b数组里的个数
for (int k = 0; k < n; k++)
//遍历a 把当前不作为算数的数放b里
{
if (k != i && k != j)
b[m++] = a[k];
}
//然后就开始四则运算的实验了
b[m] = a[i] + a[j];
if (dfs(b, m + 1))
return true;
b[m] = a[i] - a[j]; //减有两种
if (dfs(b, m + 1))
return true;
b[m] = a[j] - a[i];
if (dfs(b, m + 1))
return true;
b[m] = a[i] * a[j];
if (dfs(b, m + 1))
return true;
if (a[j] != 0) //排除分母为0的情况
{
b[m] = a[i] / a[j];
if (dfs(b, m + 1))
return true;
}
if (a[i] != 0)
{
b[m] = a[j] / a[i];
if (dfs(b, m + 1))
return true;
}
}
}
return false;//如果上面试了都不能行 那就不行
}
int main()
{
double a[5];
for (int i = 0; i < 4; i++)
cin >> a[i];
if (dfs(a, 4))
cout << "YES";
else
cout << "NO";
return 0;
}