递归:递归函数调用自身(时间和空间的消耗),实现更简洁,性能不如循环
循环:性能优于递归,
package algorithmBasic; 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; 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); } }
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)