Fix: recursion bug for JS and TS (#1028)

pull/1031/head
Justin Tse 11 months ago committed by GitHub
parent edf3f3e33a
commit 0f5b924036
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

@ -20,12 +20,12 @@ function forLoopRecur(n) {
const stack = []; const stack = [];
let res = 0; let res = 0;
// 递:递归调用 // 递:递归调用
for (let i = 1; i <= n; i++) { for (let i = n; i > 0; i--) {
// 通过“入栈操作”模拟“递” // 通过“入栈操作”模拟“递”
stack.push(i); stack.push(i);
} }
// 归:返回结果 // 归:返回结果
while (stack.length) { while (stack.length) {
// 通过“出栈操作”模拟“归” // 通过“出栈操作”模拟“归”
res += stack.pop(); res += stack.pop();
} }

@ -20,12 +20,12 @@ function forLoopRecur(n: number): number {
const stack: number[] = []; const stack: number[] = [];
let res: number = 0; let res: number = 0;
// 递:递归调用 // 递:递归调用
for (let i = 1; i <= n; i++) { for (let i = n; i > 0; i--) {
// 通过“入栈操作”模拟“递” // 通过“入栈操作”模拟“递”
stack.push(i); stack.push(i);
} }
// 归:返回结果 // 归:返回结果
while (stack.length) { while (stack.length) {
// 通过“出栈操作”模拟“归” // 通过“出栈操作”模拟“归”
res += stack.pop(); res += stack.pop();
} }
@ -67,4 +67,4 @@ console.log(`尾递归函数的求和结果 res = ${res}`);
res = fib(n); res = fib(n);
console.log(`斐波那契数列的第 ${n} 项为 ${res}`); console.log(`斐波那契数列的第 ${n} 项为 ${res}`);
export {}; export { };

Loading…
Cancel
Save