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

* feat: Add javascript and typescript code in chapter_computational_complexity

* docs: Update code comment

* style: update code order th same with java
pull/791/head
jmin 1 year ago committed by GitHub
parent 4b5e21d0d9
commit 26bf0c5a78
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

@ -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}`);

@ -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}`);

Loading…
Cancel
Save