mirror of
https://github.com/krahets/hello-algo.git
synced 2025-07-05 21:19:41 +08:00
Add comparison between iteration and recursion.
Fix the figure of tail recursion. Fix two links.
This commit is contained in:
@ -8,7 +8,7 @@ package chapter_computational_complexity;
|
||||
|
||||
public class iteration {
|
||||
/* for 循环 */
|
||||
public static int forLoop(int n) {
|
||||
static int forLoop(int n) {
|
||||
int res = 0;
|
||||
// 循环求和 1, 2, ..., n-1, n
|
||||
for (int i = 1; i <= n; i++) {
|
||||
@ -18,7 +18,7 @@ public class iteration {
|
||||
}
|
||||
|
||||
/* while 循环 */
|
||||
public static int whileLoop(int n) {
|
||||
static int whileLoop(int n) {
|
||||
int res = 0;
|
||||
int i = 1; // 初始化条件变量
|
||||
// 循环求和 1, 2, ..., n-1, n
|
||||
@ -30,7 +30,7 @@ public class iteration {
|
||||
}
|
||||
|
||||
/* while 循环(两次更新) */
|
||||
public static int whileLoopII(int n) {
|
||||
static int whileLoopII(int n) {
|
||||
int res = 0;
|
||||
int i = 1; // 初始化条件变量
|
||||
// 循环求和 1, 4, ...
|
||||
@ -44,7 +44,7 @@ public class iteration {
|
||||
}
|
||||
|
||||
/* 双层 for 循环 */
|
||||
public static String nestedForLoop(int n) {
|
||||
static String nestedForLoop(int n) {
|
||||
StringBuilder res = new StringBuilder();
|
||||
// 循环 i = 1, 2, ..., n-1, n
|
||||
for (int i = 1; i <= n; i++) {
|
||||
|
@ -6,9 +6,11 @@
|
||||
|
||||
package chapter_computational_complexity;
|
||||
|
||||
import java.util.Stack;
|
||||
|
||||
public class recursion {
|
||||
/* 递归 */
|
||||
public static int recur(int n) {
|
||||
static int recur(int n) {
|
||||
// 终止条件
|
||||
if (n == 1)
|
||||
return 1;
|
||||
@ -18,8 +20,27 @@ public class recursion {
|
||||
return n + res;
|
||||
}
|
||||
|
||||
/* 使用迭代模拟递归 */
|
||||
static int forLoopRecur(int n) {
|
||||
// 使用一个显式的栈来模拟系统调用栈
|
||||
Stack<Integer> stack = new Stack<>();
|
||||
int res = 0;
|
||||
// 递:递归调用
|
||||
for (int i = n; i > 0; i--) {
|
||||
// 通过“入栈操作”模拟“递”
|
||||
stack.push(i);
|
||||
}
|
||||
// 归:返回结果
|
||||
while (!stack.isEmpty()) {
|
||||
// 通过“出栈操作”模拟“归”
|
||||
res += stack.pop();
|
||||
}
|
||||
// res = 1+2+3+...+n
|
||||
return res;
|
||||
}
|
||||
|
||||
/* 尾递归 */
|
||||
public static int tailRecur(int n, int res) {
|
||||
static int tailRecur(int n, int res) {
|
||||
// 终止条件
|
||||
if (n == 0)
|
||||
return res;
|
||||
@ -28,7 +49,7 @@ public class recursion {
|
||||
}
|
||||
|
||||
/* 斐波那契数列:递归 */
|
||||
public static int fib(int n) {
|
||||
static int fib(int n) {
|
||||
// 终止条件 f(1) = 0, f(2) = 1
|
||||
if (n == 1 || n == 2)
|
||||
return n - 1;
|
||||
@ -46,6 +67,9 @@ public class recursion {
|
||||
res = recur(n);
|
||||
System.out.println("\n递归函数的求和结果 res = " + res);
|
||||
|
||||
res = forLoopRecur(n);
|
||||
System.out.println("\n使用迭代模拟递归求和结果 res = " + res);
|
||||
|
||||
res = tailRecur(n, 0);
|
||||
System.out.println("\n尾递归函数的求和结果 res = " + res);
|
||||
|
||||
|
Reference in New Issue
Block a user