1.通过编写普通的递归和记忆型的递归输出执行代码的时间,可以发现数据量大的情况下,记忆型的递归是耗时是比较短的,而普通的递归耗时非常长
所以有的时候遇到重复子问题使用递归来解决的时候可以在普通的递归的代码上改进变成记忆型的递归那么耗时会比较短,提高代码的运行性能
2. 下面是具体的代码:
import java.util.Scanner;
public class Main {
static int rec[];
static int v1 = 0;
static int v2 = 0;
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
rec = new int[n];
rec[0] = 1;
rec[1] = 1;
long start = System.currentTimeMillis();
int res = f1(n - 1);
System.out.println(res);
long end1 = System.currentTimeMillis();
System.out.println("记忆型递归耗时: " +(end1 - start));
res = f2(n - 1);
System.out.println(res);
long end2 = System.currentTimeMillis();
System.out.println("普通递归耗时: "+(end2 - end1));
sc.close();
}
private static int f2(int n){
if(n == 0 || n == 1) return 1;
return f2(n - 1) + f2(n - 2);
}
private static int f1(int n){
if(n == 0 || n == 1) return 1;
if(rec[n] > 0){
return rec[n];
}else{
v1 += f1(n - 1);
v2 = v1 + f1(n - 2);
rec[n] = v2;
return v2;
}
}
}
控制台输入40
输入大于40的时候发现普通递归计算非常慢,耗时非常大,可见记忆型递归代码运行的优越性,这也是使用空间换时间的完美体现,消耗一定的内存来减小代码的运行时间