展平多级双向链表之回溯或栈替代

前言

对于递归来将,可以利用其回溯来做事,但是一定要懂递归的核心在于将大问题分解成多个独立相同的小问题,递归代码非常简洁,但包容性很低。
除此之外,还可以用后出先进的栈来模拟回溯。

一、案例

在这里插入图片描述
在这里插入图片描述

二、题解

1、回溯

public Node flatten(Node head) {
        //回溯解决问题,能用回溯,就可以用栈替代解决试试。
        recursion(head);
        return head;
    }

    private Node recursion(Node head) {
        if (head == null) return null;
        Node child = recursion(head.child);
        Node next = recursion(head.next);
        if (child == null && next == null) return head;
        if (child != null && next != null) {
            Node n = head.next;
            head.next = head.child;
            head.child = null;
            head.next.prev = head;
            child.next = n;
            n.prev = child;
            return next;
        }
        if (child == null && next != null) return next;

        head.next = head.child;
        head.child.prev = head;
        head.child = null;
        return child;
    }

2、栈

//方法二:用栈模拟链表需要的回溯操作
    public Node flatten2(Node head) {
        if (head == null) return null;
        //回溯解决问题,能用回溯,就可以用栈替代解决试试。
        Stack<Node> cache = new Stack<>();

        recursion(head, cache);

        Node pre = cache.pop();
        while (!cache.isEmpty()) {
            Node node = cache.pop();

            if (node.next != pre) {
                node.next = pre;
                pre.prev = node;
            }
            node.child = null;
            pre = node;
        }
        head.child = null;
        return head;
    }

    private void recursion(Node head, Stack<Node> cache) {
        if (head == null) return;

        cache.push(head);

        recursion(head.child, cache);
        recursion(head.next, cache);
    }

    // Definition for a Node.
    class Node {
        public int val;
        public Node prev;
        public Node next;
        public Node child;
    }

总结

1)递归代码简洁,但是包容性低,一定要将大问题分解成多个独立相同的小问题。
2)栈与回溯思路类似,要保持栈对回溯的敏感性,以及栈和回溯对单向链表的敏感性,才能转换问题,举一反三。

参考文献

[1] LeetCode 原题

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值