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

报错内容

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;
}

如果有帮助,请点个~

你可能感兴趣的:(关于报错)