Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: Add javascript and typescript code in chapter_computational_com… #780

Merged
merged 3 commits into from
Sep 24, 2023
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 22 additions & 0 deletions codes/javascript/chapter_computational_complexity/recursion.js
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,25 @@ function fib(n) {
return 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 = n + ... + 3 + 2 + 1
return res;
}

/* Driver Code */
const n = 5;
let res;
Expand All @@ -44,3 +63,6 @@ console.log(`尾递归函数的求和结果 res = ${res}`);

res = fib(n);
console.log(`斐波那契数列的第 ${n} 项为 ${res}`);

res = forLoopRecur(n);
console.log(`递归转化为迭代的求和结果为 res = ${res}`);
21 changes: 21 additions & 0 deletions codes/typescript/chapter_computational_complexity/recursion.ts
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,24 @@ function fib(n: number): number {
return 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 = n + ... + 3 + 2 + 1
return res;
}
/* Driver Code */
const n = 5;
let res: number;
Expand All @@ -45,4 +63,7 @@ console.log(`尾递归函数的求和结果 res = ${res}`);
res = fib(n);
console.log(`斐波那契数列的第 ${n} 项为 ${res}`);

res = forLoopRecur(n);
console.log(`递归转化为迭代的求和结果为 res = ${res}`);

export {};