Java递归与循环

家电修理 2023-07-16 19:17www.caominkang.com电器维修

递归递归函数调用自身(时间和空间的消耗),实现更简洁,性能不如循环
循环性能优于递归,

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 = ne 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 = ne DiGui();
		int f = basic.f(40);
		System.out.println(f);


	}
}


Copyright © 2016-2025 www.caominkang.com 曹敏电脑维修网 版权所有 Power by