国产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

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


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

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

  1. 堆疊溢位:深度遞歸呼叫可能會(huì)耗盡呼叫堆疊,導(dǎo)致堆疊溢位。使用顯式堆疊可以避免這個(gè)問(wèn)題。
  2. 效率:迭代解決方案通常更節(jié)省內(nèi)存,因?yàn)樗鼈儾恍枰S護(hù)呼叫堆疊的開(kāi)銷(xiāo)。
  3. 更好的控制:使用顯式堆疊可以讓您更好地控制演算法的執(zhí)行,特別是在涉及回溯時(shí)。

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

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


通用模板

1. 遞歸函數(shù)(範(fàn)例)

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)行的遞歸呼叫。

  3. 基本條件處理:

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

  4. 處理目前狀態(tài):

    處理當(dāng)前迭代的狀態(tài)(相當(dāng)於當(dāng)前遞歸呼叫時(shí)發(fā)生的處理)。

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

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


轉(zhuǎn)換範(fà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)換為迭代的範(fàn)例

範(fà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è)例子中,堆疊明確地保存了要存取的節(jié)點(diǎn),我們使用循環(huán)來(lái)模擬遞歸呼叫。


範(fàn)例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);
            }
        }
    }
}

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


範(fàn)例 3:產(chǎn)生子集(回溯)

用於產(chǎn)生集合子集的回溯方法可以像這樣遞歸地實(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ù)呼叫。 currentSubset 被就地修改,堆疊透過(guò)將新?tīng)顟B(tài)推送到其上來(lái)處理回溯。


範(fàn)例 4:生成排列

要產(chǎn)生集合的所有排列,通常使用遞歸:

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ǔ)存排列的目前狀態(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í)行。這些範(fàn)例應(yīng)該作為指南來(lái)幫助您解決自己程式碼中的類(lèi)似問(wèn)題。

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

本網(wǎng)站聲明
本文內(nèi)容由網(wǎng)友自願(yuàn)投稿,版權(quán)歸原作者所有。本站不承擔(dān)相應(yīng)的法律責(zé)任。如發(fā)現(xiàn)涉嫌抄襲或侵權(quán)的內(nèi)容,請(qǐng)聯(lián)絡(luò)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

用於從照片中去除衣服的線(xiàn)上人工智慧工具。

Clothoff.io

Clothoff.io

AI脫衣器

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)

熱門(mén)話(huà)題

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ù)類(lèi)型 JavaScript:探索用於高效編碼的數(shù)據(jù)類(lèi)型 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)用戶(hù)操作的時(shí)機(jī)和方式。

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

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

See all articles