diff --git a/codes/javascript/chapter_computational_complexity/recursion.js b/codes/javascript/chapter_computational_complexity/recursion.js index 48538ac79b..fce0edfd6a 100644 --- a/codes/javascript/chapter_computational_complexity/recursion.js +++ b/codes/javascript/chapter_computational_complexity/recursion.js @@ -14,6 +14,25 @@ function recur(n) { return n + res; } +/* 递归转化为迭代 */ +function forLoopRecur(n) { + // 使用一个显式的栈来模拟系统调用栈 + const stack = []; + let res = 0; + // 递:递归调用 + for (let i = 1; i <= n; i++) { + // 通过“入栈操作”模拟“递” + stack.push(i); + } + // 归:返回结果 + while (stack.length) { + // 通过“出栈操作”模拟“归” + res += stack.pop(); + } + // res = 1+2+3+...+n + return res; +} + /* 尾递归 */ function tailRecur(n, res) { // 终止条件 @@ -39,8 +58,12 @@ let res; res = recur(n); console.log(`递归函数的求和结果 res = ${res}`); +res = forLoopRecur(n); +console.log(`递归转化为迭代的求和结果 res = ${res}`); + res = tailRecur(n, 0); console.log(`尾递归函数的求和结果 res = ${res}`); res = fib(n); console.log(`斐波那契数列的第 ${n} 项为 ${res}`); + diff --git a/codes/typescript/chapter_computational_complexity/recursion.ts b/codes/typescript/chapter_computational_complexity/recursion.ts index 88e14715c0..fff703c99c 100644 --- a/codes/typescript/chapter_computational_complexity/recursion.ts +++ b/codes/typescript/chapter_computational_complexity/recursion.ts @@ -14,6 +14,25 @@ function recur(n: number): number { return n + res; } +/* 递归转化为迭代 */ +function forLoopRecur(n: number): number { + // 使用一个显式的栈来模拟系统调用栈 + const stack: number[] = []; + let res: number = 0; + // 递:递归调用 + for (let i = 1; i <= n; i++) { + // 通过“入栈操作”模拟“递” + stack.push(i); + } + // 归:返回结果 + while (stack.length) { + // 通过“出栈操作”模拟“归” + res += stack.pop(); + } + // res = 1+2+3+...+n + return res; +} + /* 尾递归 */ function tailRecur(n: number, res: number): number { // 终止条件 @@ -39,6 +58,9 @@ let res: number; res = recur(n); console.log(`递归函数的求和结果 res = ${res}`); +res = forLoopRecur(n); +console.log(`递归转化为迭代的求和结果 res = ${res}`); + res = tailRecur(n, 0); console.log(`尾递归函数的求和结果 res = ${res}`);