我是一名有用的助手,可以为您进行文本翻译。以下是需要翻译的内容:
此外,乘法只能在连续的情况下使用最多5次(而不是总共),因此n=20以下的任何内容都可以适合整数。为了解决这个问题,我编写了这个递归树,但在更高的值(如n=15)时,我的输出变得不正确。
我已经尝试诊断了将近一周,但仍无法使其正常工作...我试图使代码尽可能易读,并在必要时进行了注释。只是为了解释代码的作用-它构建一个树,其中(+,-和*)是每次迭代的分支。每个节点都是到该点的表达式的总和,因此当我们达到深度= n时,所有结束节点都是所有可能的表达式总和-我们所要做的就是检查它们是否等于n。如下所示:
我有一个作业卡在那里很久了。我应该考虑从1到N的所有可能表达式,就像这样:
n = 5;
1 % 2 % 3 % 4 % 5 = ?
其中%可以是加法、减法或乘法(+,-,*)。 我的任务是考虑所有可能的操作组合,并计算有多少个结果表达式等于n本身。
例如,对于n=4,答案为1,因为只有一个等于n的表达式。
1 + 2 - 3 + 4 = 4
还有几个需要注意的地方 - 乘法比其他两种运算符优先级更高。例如:
1 + 2 + 3 * 4 * 5 + 6
需要解析为
1 + 2 + (3 * 4 * 5) + 6
此外,乘法只能在连续的情况下使用最多5次(而不是总共),因此n=20以下的任何内容都可以适合整数。为了解决这个问题,我编写了这个递归树,但在更高的值(如n=15)时,我的输出变得不正确。
[N ] - [Expected result] [My program's result]
[5 ] - [ 3] [ 3]
[6 ] - [ 1] [ 1]
[9 ] - [ 27] [ 27]
[15] - [ 3932] [ 3911]
[16] - [ 9803] [ 9327]
[17] - [ 23209] [ 22942]
我已经尝试诊断了将近一周,但仍无法使其正常工作...我试图使代码尽可能易读,并在必要时进行了注释。只是为了解释代码的作用-它构建一个树,其中(+,-和*)是每次迭代的分支。每个节点都是到该点的表达式的总和,因此当我们达到深度= n时,所有结束节点都是所有可能的表达式总和-我们所要做的就是检查它们是否等于n。如下所示:
#include <stdio.h>
int n;
int result = 0;
void tree(int depth, int sum, int mul, int last) {
//DEPTH = recursion from 1 to n
//SUM = the sum of the expression
//MUL = counter to track how many consecutive multiplications have been done
//LAST = previous number added to sum
//if n nodes reached
if (depth == n) {
if (sum == n) {
//count result
result++;
}
return;
}
//build tree
depth++;
if (mul % 5 != 0) { //if multiplication hasn't been used 5x in a row
tree(depth, (sum - last) + (last * depth), mul + 1, last * depth);
} else {
//else dont build a multiplication branch, but reset the counter
mul = 1;
}
//build addition and subtraction trees
tree(depth, sum + depth, mul, depth);
tree(depth, sum - depth, mul, depth * -1);
}
int main(int argc, char **argv) {
scanf("%i", &n);
tree(1, 1, 1, 1);
printf("%i\n", result);
return 0;
}
更新1:MUL计数器已校正
#include <stdio.h>
int n;
int result = 0;
void tree(int depth, int sum, int mul, int last) {
//DEPTH = recursion from 1 to n
//SUM = the sum of the expression
//MUL = counter to track how many consecutive multiplications have been done
//LAST = previous number added to sum
//if n nodes reached
if (depth == n) {
if (sum == n) {
//count result
result++;
}
return;
}
//build tree
depth++;
if (mul < 5) { //if multiplication hasn't been used 5x in a row
tree(depth, (sum - last) + (last * depth), mul + 1, last * depth);
} else {
//else dont build a multiplication branch, but reset the counter
mul = 0;
}
//build addition and subtraction trees
tree(depth, sum + depth, mul, depth);
tree(depth, sum - depth, mul, depth * -1);
}
int main(int argc, char **argv) {
scanf("%i", &n);
tree(1, 1, 0, 1);
printf("%i\n", result);
return 0;
}
更新内容:根据答案更正计数器和起始值,但在高值时程序仍会产生不正确的结果,更新数据如下:
[N ] - [Expected result] [My program's result]
[5 ] - [ 3] [ 3]
[6 ] - [ 1] [ 1]
[9 ] - [ 27] [ 27]
[15] - [ 3932] [ 3924]
[16] - [ 9803] [ 9781]
[17] - [ 23209] [ 23121]
结果更接近了!!
0
,但是如果你没有递归进行乘法运算,你只会将mul
重置为0
。这是不正确的。 - chqrlie