Java 将递归方法转化为迭代方法
我必须创建两个做同样事情的方法。这些方法必须计算0-30之间的数字的L(n),其中L(n)定义为 L(0)=1 L(1)=1 L(n)=L(n-1)+L(n-2)+1; 当n>1时 第一个方法必须使用递归编写,我成功地做到了这一点,第二个方法必须使用迭代(数组和for循环)编写 第一种方法) 我主要在第一个方法中添加了这个Java 将递归方法转化为迭代方法,java,algorithm,recursion,iteration,Java,Algorithm,Recursion,Iteration,我必须创建两个做同样事情的方法。这些方法必须计算0-30之间的数字的L(n),其中L(n)定义为 L(0)=1 L(1)=1 L(n)=L(n-1)+L(n-2)+1; 当n>1时 第一个方法必须使用递归编写,我成功地做到了这一点,第二个方法必须使用迭代(数组和for循环)编写 第一种方法) 我主要在第一个方法中添加了这个 public static int rec(int x) { if (x == 0) return 1; if (x == 1) return 1; else r
public static int rec(int x) {
if (x == 0) return 1;
if (x == 1) return 1;
else return rec(x - 1) + rec(x - 2) + 1;
}
int x = 0;
while (x <= 30) {
System.out.println(rec(x));
x++;
}
intx=0;
(x想想你的代码在做什么-
for ( int i = 0 ; i < x.length ; i++){
long returnvalue = x[i-1]+x[i-2]+1; // every iteration you are resetting returnvalue.
}
请注意,在迭代版本中,在循环开始之前只定义一次returnValue。如何将L视为数组,然后执行以下赋值:
L(0)=1
L(1)=1
对于第三步,您必须编写一个循环,计算并存储L[2]到L[30]的值。在循环的每次迭代中,前两个值都将在L中,因此您可以直接使用它们。您非常接近-您需要在迭代解决方案中保留历史记录:
public static long iter(long x) {
long result = 0;
// Make a 2-length array for my history.
long[] history = new long[2];
for (int i = 0; i <= x; i++) {
if (i < 2) {
result = 1;
} else {
result = history[0] + history[1] + 1;
}
// Maintain my history.
history[0] = history[1];
history[1] = result;
}
return result;
}
公共静态长iter(长x){
长结果=0;
//为我的历史记录创建一个2长度数组。
长[]历史=新长[2];
因为(inti=0;i所以我最终能够解决它:(感谢所有的帮助,非常感谢)
公共类Aufgabe1{
//使用0到30之间的所有整数调用iter和rec,并打印结果
//(无空行或其他输出)
公共静态void main(字符串[]args){
//TODO:实现是您的任务
int x=0;
虽然(x)您应该在for循环中累积结果,但现在您只需重新分配它。请注意,根据您老师的要求级别,他可能期望递归方法的更有效实现。这有一些缺陷,最大的缺陷是当i<2时,分配将尝试求负指数x
for ( int i = 0 ; i < x.length ; i++){
returnvalue = returnvalue + x[i-1]+x[i-2]+1;
}
returnvalue += x[i-1]+x[i-2]+1;
public static long iter(long x) {
long result = 0;
// Make a 2-length array for my history.
long[] history = new long[2];
for (int i = 0; i <= x; i++) {
if (i < 2) {
result = 1;
} else {
result = history[0] + history[1] + 1;
}
// Maintain my history.
history[0] = history[1];
history[1] = result;
}
return result;
}
public class Aufgabe1 {
// invokes iter as well as rec with all integers from 0 to 30 and prints the results
// (without empty lines or other output)
public static void main(String[] args) {
// TODO: Implementation is your task
int x = 0;
while (x <= 30) {
System.out.println(rec(x));
x++;
}
long [] longArr = new long[31];
iter(longArr);
}
public static int rec(int x) {
if (x == 0) return 1;
if (x == 1) return 1;
else return rec(x - 1) + rec(x - 2) + 1;
}
public static void iter(long[] n) {
for (int i = 0; i < n.length; i++) {
if (i == 0 || i == 1) {
n[i] = 1;
} else {
n[i] = n[i - 1] + n[i - 2] + 1;
}
System.out.println(n[i]);
}
}
}