leetcode报错之 ERROR: AddressSanitizer: stack-overflow on address ...

本文探讨了在LeetCode中遇到的ERROR: AddressSanitizer: stack-overflow错误,原因是递归深度过大。为了解决这个问题,提出了两种替代实现:使用广度优先搜索(BFS)和显式栈实现深度优先搜索(DFS)。并提供了相关代码模板。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

报错内容

AddressSanitizer:DEADLYSIGNAL
=================================================================
==45==ERROR: AddressSanitizer: stack-overflow on address 0x7ffc1b6a1ff8 (pc 0x7f71b6e7d3e0 bp 0x000000000010 sp 0x7ffc1b6a1fe0 T0)
    #0 0x7f71b6e7d3df  (/usr/lib/x86_64-linux-gnu/libasan.so.5+0x2b3df)
    #1 0x7f71b6e7daaa  (/usr/lib/x86_64-linux-gnu/libasan.so.5+0x2baaa)
    #2 0x7f71b6e7a046  (/usr/lib/x86_64-linux-gnu/libasan.so.5+0x28046)
    #3 0x7f71b6f5e04e in malloc (/usr/lib/x86_64-linux-gnu/libasan.so.5+0x10c04e)
SUMMARY: AddressSanitizer: stack-overflow (/usr/lib/x86_64-linux-gnu/libasan.so.5+0x2b3df) 
==45==ABORTING

翻译

栈溢出。

原因

递归的深度太高。

递归法解决方案的优点是它更容易实现。但是存在一个很大的缺点:如果递归的深度太高,我们将遭受堆栈溢出

解决方法

改变实现方法。

方案有二:

  1. 使用BFS;
  2. 使用显式栈实现DFS.

解决方法相关

BFS 代码模板

Java伪代码

/**
 * Return the length of the shortest path between root and target node.
 */
int BFS(Node root, Node target) {
    Queue<Node> queue;  // store all nodes which are waiting to be processed
    int step = 0;       // number of steps neeeded from root to current node
    // initialize
    add root to queue;
    // BFS
    while (queue is not empty) {
        step = step + 1;
        // iterate the nodes which are already in the queue
        int size = queue.size();
        for (int i = 0; i < size; ++i) {
            Node cur = the first node in queue;
            return step if cur is target;
            for (Node next : the neighbors of cur) {
                add next to queue;
            }
            remove the first node from queue;
        }
    }
    return -1;          // there is no path from root to target
}

显式栈 代码模板

Java伪代码

/*
 * Return true if there is a path from cur to target.
 */
boolean DFS(int root, int target) {
    Set<Node> visited;
    Stack<Node> s;
    add root to s;
    while (s is not empty) {
        Node cur = the top element in s;
        return true if cur is target;
        for (Node next : the neighbors of cur) {
            if (next is not in visited) {
                add next to s;
                add next to visited;
            }
        }
        remove cur from s;
    }
    return false;
}

如果有帮助,请点个👍~

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

AuthurLEE

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值