From 0f5b924036bc6bab24451945af08267d589ab36d Mon Sep 17 00:00:00 2001 From: Justin Tse Date: Sat, 6 Jan 2024 16:29:39 +0800 Subject: [PATCH] Fix: recursion bug for JS and TS (#1028) --- .../chapter_computational_complexity/recursion.js | 4 ++-- .../chapter_computational_complexity/recursion.ts | 6 +++--- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/codes/javascript/chapter_computational_complexity/recursion.js b/codes/javascript/chapter_computational_complexity/recursion.js index 7c406a972..c64e03538 100644 --- a/codes/javascript/chapter_computational_complexity/recursion.js +++ b/codes/javascript/chapter_computational_complexity/recursion.js @@ -20,12 +20,12 @@ function forLoopRecur(n) { const stack = []; let res = 0; // 递:递归调用 - for (let i = 1; i <= n; i++) { + for (let i = n; i > 0; i--) { // 通过“入栈操作”模拟“递” stack.push(i); } // 归:返回结果 - while (stack.length) { + while (stack.length) { // 通过“出栈操作”模拟“归” res += stack.pop(); } diff --git a/codes/typescript/chapter_computational_complexity/recursion.ts b/codes/typescript/chapter_computational_complexity/recursion.ts index b8786d08c..adc1a12a4 100644 --- a/codes/typescript/chapter_computational_complexity/recursion.ts +++ b/codes/typescript/chapter_computational_complexity/recursion.ts @@ -20,12 +20,12 @@ function forLoopRecur(n: number): number { const stack: number[] = []; let res: number = 0; // 递:递归调用 - for (let i = 1; i <= n; i++) { + for (let i = n; i > 0; i--) { // 通过“入栈操作”模拟“递” stack.push(i); } // 归:返回结果 - while (stack.length) { + while (stack.length) { // 通过“出栈操作”模拟“归” res += stack.pop(); } @@ -67,4 +67,4 @@ console.log(`尾递归函数的求和结果 res = ${res}`); res = fib(n); console.log(`斐波那契数列的第 ${n} 项为 ${res}`); -export {}; +export { };