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
10 changes: 5 additions & 5 deletions codes/javascript/chapter_computational_complexity/recursion.js
Original file line number Diff line number Diff line change
Expand Up @@ -34,20 +34,20 @@ function fib(n) {

/* 递归转化为迭代 */
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
// res = 1+2+3+...+n
return res;
}

Expand All @@ -65,4 +65,4 @@ res = fib(n);
console.log(`斐波那契数列的第 ${n} 项为 ${res}`);

res = forLoopRecur(n);
console.log(`递归转化为迭代的求和结果为 res = ${res}`);
console.log(`递归转化为迭代的求和结果 res = ${res}`);
krahets marked this conversation as resolved.
Show resolved Hide resolved
10 changes: 5 additions & 5 deletions codes/typescript/chapter_computational_complexity/recursion.ts
Original file line number Diff line number Diff line change
Expand Up @@ -34,20 +34,20 @@ function fib(n: number): number {

/* 递归转化为迭代 */
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
// res = 1+2+3+...+n
return res;
}
/* Driver Code */
Expand All @@ -64,6 +64,6 @@ res = fib(n);
console.log(`斐波那契数列的第 ${n} 项为 ${res}`);

res = forLoopRecur(n);
console.log(`递归转化为迭代的求和结果为 res = ${res}`);
console.log(`递归转化为迭代的求和结果 res = ${res}`);
krahets marked this conversation as resolved.
Show resolved Hide resolved

export {};