js实现递归算法

什么是递归算法:

递归是一种解决问题的方法,其中一个函数调用自身以解决较小的子问题,直到达到基线条件。递归算法在解决具有重复子结构的问题时非常有用。

递归实现斐波那契数列

斐波那契数列是一个数列,其中每个数都是前两个数的和。通常定义为 F(0) = 0, F(1) = 1, 然后 F(n) = F(n-1) + F(n-2)。

function fibonacci(n) {
    // 基线条件: n 为 0 或 1 时,返回 n
    if (n <= 1) {
        return n;
    }
    // 递归调用
    return fibonacci(n - 1) + fibonacci(n - 2);
}

// 使用示例
console.log(fibonacci(6)); // 输出: 8

递归实现深度复制

function deepClone(obj) {
    // 基线条件: 如果 obj 不是对象或数组,直接返回
    if (obj === null || typeof obj !== 'object') {
        return obj;
    }

    // 如果 obj 是数组
    if (Array.isArray(obj)) {
        return obj.map(item => deepClone(item));
    }

    // 如果 obj 是对象
    const clone = {};
    for (const key in obj) {
        if (obj.hasOwnProperty(key)) {
            clone[key] = deepClone(obj[key]);
        }
    }
    return clone;
}

// 使用示例
const original = {
    name: 'Alice',
    age: 30,
    address: {
        city: 'Wonderland',
        postalCode: '12345'
    },
    hobbies: ['reading', 'hiking'],
    getDetails: function() {
        return `${this.name}, ${this.age}`;
    }
};

const copied = deepClone(original);

console.log(copied); // 输出: 深度复制后的对象
console.log(copied.address === original.address); // 输出: false, 确保地址对象已被复制
console.log(copied.hobbies === original.hobbies); // 输出: false, 确保爱好数组已被复制
console.log(copied.getDetails === original.getDetails); // 输出: true, 函数是按引用复制的
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值