递归:递归函数调用自身(时间和空间的消耗),实现更简洁,性能不如循环
循环:性能优于递归,
package algorithmBasic;
/**
* @author kegekeqi
* @version 1.0
* @date 2021-12-12 10:59
*/
public class DiGui {
public int f(int n) {
if (n <= 0) {
return 0;
} else if (n == 1) {
return 1;
}
return f(n - 1) + f(n - 2);
}
public static void main(String[] args) {
DiGui basic = new DiGui();
int f = basic.f(40);
System.out.println(f);
}
}
package algorithmBasic;
/**
* @author kegekeqi
* @version 1.0
* @date 2021-12-12 11:08
*/
public class ForMethod {
public int f(int n) {
if (n <= 0) {
return 0;
} else if (n == 1) {
return 1;
}
int last = 0, result = 1;
for (int i = 2; i <= n; i++) {
result += last;
//上一个给回去
last = result - last;
}
return result;
}
public static void main(String[] args) {
DiGui basic = new DiGui();
int f = basic.f(40);
System.out.println(f);
}
}