国产av日韩一区二区三区精品,成人性爱视频在线观看,国产,欧美,日韩,一区,www.成色av久久成人,2222eeee成人天堂

首頁(yè) web前端 js教程 使用堆棧將遞歸轉(zhuǎn)換為迭代:實(shí)用指南

使用堆棧將遞歸轉(zhuǎn)換為迭代:實(shí)用指南

Dec 22, 2024 pm 06:45 PM

Converting Recursion to Iteration Using a Stack: A Practical Guide

遞歸是計(jì)算機(jī)科學(xué)中的一項(xiàng)強(qiáng)大技術(shù),通常用于樹(shù)遍歷、深度優(yōu)先搜索和回溯算法等任務(wù)。然而,由于函數(shù)調(diào)用和維護(hù)調(diào)用堆棧的開(kāi)銷,遞歸在時(shí)間和空間方面的效率可能較低。在某些情況下,使用顯式堆棧來(lái)模擬遞歸調(diào)用,將遞歸轉(zhuǎn)換為迭代方法是有益的。本文提供了在 JavaScript 中使用堆棧將遞歸算法轉(zhuǎn)換為迭代算法的分步指南。


為什么將遞歸轉(zhuǎn)換為迭代?

您可能想要將遞歸轉(zhuǎn)換為迭代的原因有幾個(gè):

  1. 堆棧溢出:深度遞歸調(diào)用可能耗盡調(diào)用堆棧,導(dǎo)致堆棧溢出。使用顯式堆棧可以避免這個(gè)問(wèn)題。
  2. 效率:迭代解決方案通常更節(jié)省內(nèi)存,因?yàn)樗鼈儾恍枰S護(hù)調(diào)用堆棧的開(kāi)銷。
  3. 更好的控制:使用顯式堆??梢宰屇玫乜刂扑惴ǖ膱?zhí)行,特別是在涉及回溯時(shí)。

使用堆棧將遞歸轉(zhuǎn)換為迭代的模板

當(dāng)使用堆棧將遞歸函數(shù)轉(zhuǎn)換為迭代函數(shù)時(shí),不同類型的算法(例如樹(shù)遍歷、回溯問(wèn)題或圖遍歷)的一般方法保持相似。下面是一個(gè)靈活的模板,可以適應(yīng)各種場(chǎng)景。


通用模板

1. 遞歸函數(shù)(示例)

function recursiveFunction(args) {
    // Base case
    if (baseCondition) {
        // Handle the base case
        return;
    }

    // Recursive calls
    for (let i = 0; i < someLimit; i++) {
        recursiveFunction(newArgs);
    }
}

2. 使用堆棧的迭代函數(shù)

要將上述遞歸函數(shù)轉(zhuǎn)換為迭代函數(shù),我們按照以下步驟操作:

function iterativeFunction(args) {
    // Initialize the stack
    let stack = [initialState];

    // Loop until the stack is empty
    while (stack.length > 0) {
        // Pop the current state from the stack
        let currentState = stack.pop();

        // Handle the base case (optional, since we can check on each iteration)
        if (baseCondition) {
            continue;  // Skip or handle the base case
        }

        // Process the current state
        processState(currentState);

        // Push next states onto the stack
        for (let i = 0; i < someLimit; i++) {
            let newState = generateNewState(currentState, i);
            stack.push(newState);
        }
    }
}

模板分解

  1. 初始化堆棧:

    堆棧應(yīng)使用起始狀態(tài)進(jìn)行初始化,起始狀態(tài)可以是初始參數(shù)或遍歷中的第一個(gè)節(jié)點(diǎn)。

  2. 循環(huán)堆棧:

    只要堆棧有項(xiàng)目,循環(huán)就會(huì)繼續(xù),這表示在原始函數(shù)中進(jìn)行的遞歸調(diào)用。

  3. 基本條件處理:

    在遞歸中,基本條件檢查是否需要進(jìn)一步遞歸。在迭代方法中,您可以在循環(huán)內(nèi)執(zhí)行相同的檢查。當(dāng)滿足基本條件時(shí),您可以使用繼續(xù)跳過(guò)進(jìn)一步的處理。

  4. 處理當(dāng)前狀態(tài):

    處理當(dāng)前迭代的狀態(tài)(相當(dāng)于當(dāng)前遞歸調(diào)用時(shí)發(fā)生的處理)。

  5. 推送下一個(gè)狀態(tài)

    就像遞歸函數(shù)調(diào)用新的遞歸函數(shù)一樣,在這里將下一個(gè)狀態(tài)(即要處理的函數(shù)參數(shù)或節(jié)點(diǎn))推送到堆棧上。


轉(zhuǎn)換示例:有序樹(shù)遍歷

遞歸版本:

function recursiveFunction(args) {
    // Base case
    if (baseCondition) {
        // Handle the base case
        return;
    }

    // Recursive calls
    for (let i = 0; i < someLimit; i++) {
        recursiveFunction(newArgs);
    }
}

使用堆棧的迭代版本:

function iterativeFunction(args) {
    // Initialize the stack
    let stack = [initialState];

    // Loop until the stack is empty
    while (stack.length > 0) {
        // Pop the current state from the stack
        let currentState = stack.pop();

        // Handle the base case (optional, since we can check on each iteration)
        if (baseCondition) {
            continue;  // Skip or handle the base case
        }

        // Process the current state
        processState(currentState);

        // Push next states onto the stack
        for (let i = 0; i < someLimit; i++) {
            let newState = generateNewState(currentState, i);
            stack.push(newState);
        }
    }
}

將遞歸轉(zhuǎn)換為迭代的示例

示例 1:圖上的深度優(yōu)先搜索 (DFS)

深度優(yōu)先搜索(DFS)通常使用遞歸來(lái)實(shí)現(xiàn)。這是遞歸 DFS 算法:

function inorderTraversal(root) {
    if (root === null) return;
    inorderTraversal(root.left);
    console.log(root.value);
    inorderTraversal(root.right);
}

使用堆棧的迭代版本:

function inorderTraversalIterative(root) {
    let stack = [];
    let current = root;

    while (stack.length > 0 || current !== null) {
        // Reach the leftmost node
        while (current !== null) {
            stack.push(current);
            current = current.left;
        }

        // Visit the node
        current = stack.pop();
        console.log(current.value);

        // Move to the right node
        current = current.right;
    }
}

在這個(gè)例子中,堆棧顯式地保存了要訪問(wèn)的節(jié)點(diǎn),我們使用循環(huán)來(lái)模擬遞歸調(diào)用。


示例2:中序樹(shù)遍歷(迭代)

二叉樹(shù)的中序遍歷通常是遞歸完成的。這是遞歸版本:

function dfs(graph, node, visited = new Set()) {
    if (visited.has(node)) return;
    console.log(node);
    visited.add(node);

    for (let neighbor of graph[node]) {
        dfs(graph, neighbor, visited);
    }
}

使用堆棧的迭代版本:

function dfsIterative(graph, startNode) {
    let stack = [startNode];
    let visited = new Set();

    while (stack.length > 0) {
        let node = stack.pop();

        if (visited.has(node)) continue;

        console.log(node);
        visited.add(node);

        // Add neighbors to the stack in reverse order to maintain DFS order
        for (let neighbor of graph[node].reverse()) {
            if (!visited.has(neighbor)) {
                stack.push(neighbor);
            }
        }
    }
}

在這種情況下,堆棧幫助跟蹤要訪問(wèn)的節(jié)點(diǎn),內(nèi)循環(huán)向下遍歷樹(shù)的左側(cè),直到到達(dá)最左邊的節(jié)點(diǎn)。


示例 3:生成子集(回溯)

用于生成集合子集的回溯方法可以像這樣遞歸地實(shí)現(xiàn):

function inorderTraversal(root) {
    if (root === null) return;
    inorderTraversal(root.left);
    console.log(root.value);
    inorderTraversal(root.right);
}

使用堆棧的迭代版本:

function inorderTraversalIterative(root) {
    let stack = [];
    let current = root;

    while (stack.length > 0 || current !== null) {
        // Reach the leftmost node
        while (current !== null) {
            stack.push(current);
            current = current.left;
        }

        // Visit the node
        current = stack.pop();
        console.log(current.value);

        // Move to the right node
        current = current.right;
    }
}

迭代版本使用堆棧來(lái)模擬遞歸函數(shù)調(diào)用。 currentSubset 被就地修改,堆棧通過(guò)將新?tīng)顟B(tài)推送到其上來(lái)處理回溯。


示例 4:生成排列

要生成集合的所有排列,通常使用遞歸:

function subsets(nums) {
    let result = [];
    function backtrack(start, currentSubset) {
        result.push([...currentSubset]);
        for (let i = start; i < nums.length; i++) {
            currentSubset.push(nums[i]);
            backtrack(i + 1, currentSubset);
            currentSubset.pop();
        }
    }
    backtrack(0, []);
    return result;
}

使用堆棧的迭代版本:

function subsetsIterative(nums) {
    let stack = [{start: 0, currentSubset: []}];
    let result = [];

    while (stack.length > 0) {
        let { start, currentSubset } = stack.pop();
        result.push([...currentSubset]);

        // Explore subsets by including elements from `start` onwards
        for (let i = start; i < nums.length; i++) {
            currentSubset.push(nums[i]);
            stack.push({ start: i + 1, currentSubset: [...currentSubset] });
            currentSubset.pop(); // backtrack
        }
    }

    return result;
}

這個(gè)迭代版本使用堆棧來(lái)存儲(chǔ)排列的當(dāng)前狀態(tài)?;厮菔峭ㄟ^(guò)從堆棧中壓入和彈出狀態(tài)來(lái)處理的。


示例 5:N 皇后問(wèn)題(回溯)

N 皇后問(wèn)題通常使用遞歸回溯來(lái)解決:

function permute(nums) {
    let result = [];
    function backtrack(start) {
        if (start === nums.length) {
            result.push([...nums]);
            return;
        }
        for (let i = start; i < nums.length; i++) {
            [nums[start], nums[i]] = [nums[i], nums[start]];  // swap
            backtrack(start + 1);
            [nums[start], nums[i]] = [nums[i], nums[start]];  // backtrack (swap back)
        }
    }
    backtrack(0);
    return result;
}

使用堆棧的迭代版本:

function recursiveFunction(args) {
    // Base case
    if (baseCondition) {
        // Handle the base case
        return;
    }

    // Recursive calls
    for (let i = 0; i < someLimit; i++) {
        recursiveFunction(newArgs);
    }
}

結(jié)論

使用堆棧將遞歸轉(zhuǎn)換為迭代對(duì)于許多算法來(lái)說(shuō)是一項(xiàng)很有價(jià)值的技術(shù),特別是那些涉及回溯或樹(shù)/圖遍歷的算法。通過(guò)使用顯式堆棧,我們可以避免深度遞歸,手動(dòng)管理函數(shù)狀態(tài),并確保我們更好地控制算法的執(zhí)行。這些示例應(yīng)該作為指南來(lái)幫助您解決自己代碼中的類似問(wèn)題。

以上是使用堆棧將遞歸轉(zhuǎn)換為迭代:實(shí)用指南的詳細(xì)內(nèi)容。更多信息請(qǐng)關(guān)注PHP中文網(wǎng)其他相關(guān)文章!

本站聲明
本文內(nèi)容由網(wǎng)友自發(fā)貢獻(xiàn),版權(quán)歸原作者所有,本站不承擔(dān)相應(yīng)法律責(zé)任。如您發(fā)現(xiàn)有涉嫌抄襲侵權(quán)的內(nèi)容,請(qǐng)聯(lián)系admin@php.cn

熱AI工具

Undress AI Tool

Undress AI Tool

免費(fèi)脫衣服圖片

Undresser.AI Undress

Undresser.AI Undress

人工智能驅(qū)動(dòng)的應(yīng)用程序,用于創(chuàng)建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用于從照片中去除衣服的在線人工智能工具。

Clothoff.io

Clothoff.io

AI脫衣機(jī)

Video Face Swap

Video Face Swap

使用我們完全免費(fèi)的人工智能換臉工具輕松在任何視頻中換臉!

熱工具

記事本++7.3.1

記事本++7.3.1

好用且免費(fèi)的代碼編輯器

SublimeText3漢化版

SublimeText3漢化版

中文版,非常好用

禪工作室 13.0.1

禪工作室 13.0.1

功能強(qiáng)大的PHP集成開(kāi)發(fā)環(huán)境

Dreamweaver CS6

Dreamweaver CS6

視覺(jué)化網(wǎng)頁(yè)開(kāi)發(fā)工具

SublimeText3 Mac版

SublimeText3 Mac版

神級(jí)代碼編輯軟件(SublimeText3)

Java vs. JavaScript:清除混亂 Java vs. JavaScript:清除混亂 Jun 20, 2025 am 12:27 AM

Java和JavaScript是不同的編程語(yǔ)言,各自適用于不同的應(yīng)用場(chǎng)景。Java用于大型企業(yè)和移動(dòng)應(yīng)用開(kāi)發(fā),而JavaScript主要用于網(wǎng)頁(yè)開(kāi)發(fā)。

JavaScript評(píng)論:簡(jiǎn)短說(shuō)明 JavaScript評(píng)論:簡(jiǎn)短說(shuō)明 Jun 19, 2025 am 12:40 AM

JavascriptconcommentsenceenceEncorenceEnterential gransimenting,reading and guidingCodeeXecution.1)單inecommentsareusedforquickexplanations.2)多l(xiāng)inecommentsexplaincomplexlogicorprovideDocumentation.3)

如何在JS中與日期和時(shí)間合作? 如何在JS中與日期和時(shí)間合作? Jul 01, 2025 am 01:27 AM

JavaScript中的日期和時(shí)間處理需注意以下幾點(diǎn):1.創(chuàng)建Date對(duì)象有多種方式,推薦使用ISO格式字符串以保證兼容性;2.獲取和設(shè)置時(shí)間信息可用get和set方法,注意月份從0開(kāi)始;3.手動(dòng)格式化日期需拼接字符串,也可使用第三方庫(kù);4.處理時(shí)區(qū)問(wèn)題建議使用支持時(shí)區(qū)的庫(kù),如Luxon。掌握這些要點(diǎn)能有效避免常見(jiàn)錯(cuò)誤。

為什么要將標(biāo)簽放在的底部? 為什么要將標(biāo)簽放在的底部? Jul 02, 2025 am 01:22 AM

PlacingtagsatthebottomofablogpostorwebpageservespracticalpurposesforSEO,userexperience,anddesign.1.IthelpswithSEObyallowingsearchenginestoaccesskeyword-relevanttagswithoutclutteringthemaincontent.2.Itimprovesuserexperiencebykeepingthefocusonthearticl

JavaScript與Java:開(kāi)發(fā)人員的全面比較 JavaScript與Java:開(kāi)發(fā)人員的全面比較 Jun 20, 2025 am 12:21 AM

JavaScriptIspreferredforredforwebdevelverment,而Javaisbetterforlarge-ScalebackendsystystemsandSandAndRoidApps.1)JavascriptexcelcelsincreatingInteractiveWebexperienceswebexperienceswithitswithitsdynamicnnamicnnamicnnamicnnamicnemicnemicnemicnemicnemicnemicnemicnemicnddommanipulation.2)

JavaScript:探索用于高效編碼的數(shù)據(jù)類型 JavaScript:探索用于高效編碼的數(shù)據(jù)類型 Jun 20, 2025 am 12:46 AM

javascripthassevenfundaMentalDatatypes:數(shù)字,弦,布爾值,未定義,null,object和symbol.1)numberSeadUble-eaduble-ecisionFormat,forwidevaluerangesbutbecautious.2)

什么是在DOM中冒泡和捕獲的事件? 什么是在DOM中冒泡和捕獲的事件? Jul 02, 2025 am 01:19 AM

事件捕獲和冒泡是DOM中事件傳播的兩個(gè)階段,捕獲是從頂層向下到目標(biāo)元素,冒泡是從目標(biāo)元素向上傳播到頂層。1.事件捕獲通過(guò)addEventListener的useCapture參數(shù)設(shè)為true實(shí)現(xiàn);2.事件冒泡是默認(rèn)行為,useCapture設(shè)為false或省略;3.可使用event.stopPropagation()阻止事件傳播;4.冒泡支持事件委托,提高動(dòng)態(tài)內(nèi)容處理效率;5.捕獲可用于提前攔截事件,如日志記錄或錯(cuò)誤處理。了解這兩個(gè)階段有助于精確控制JavaScript響應(yīng)用戶操作的時(shí)機(jī)和方式。

Java和JavaScript有什么區(qū)別? Java和JavaScript有什么區(qū)別? Jun 17, 2025 am 09:17 AM

Java和JavaScript是不同的編程語(yǔ)言。1.Java是靜態(tài)類型、編譯型語(yǔ)言,適用于企業(yè)應(yīng)用和大型系統(tǒng)。2.JavaScript是動(dòng)態(tài)類型、解釋型語(yǔ)言,主要用于網(wǎng)頁(yè)交互和前端開(kāi)發(fā)。

See all articles