From b620969245b44e82dc74012b3908fc8bea206447 Mon Sep 17 00:00:00 2001 From: AC_Oier Date: Fri, 24 Sep 2021 10:07:56 +0800 Subject: [PATCH] =?UTF-8?q?=E2=9C=A8update:=20Modify=20430?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- ...10\344\270\255\347\255\211\357\274\211.md" | 42 +++++++++++++++++++ 1 file changed, 42 insertions(+) diff --git "a/LeetCode/421-430/430. \346\211\201\345\271\263\345\214\226\345\244\232\347\272\247\345\217\214\345\220\221\351\223\276\350\241\250\357\274\210\344\270\255\347\255\211\357\274\211.md" "b/LeetCode/421-430/430. \346\211\201\345\271\263\345\214\226\345\244\232\347\272\247\345\217\214\345\220\221\351\223\276\350\241\250\357\274\210\344\270\255\347\255\211\357\274\211.md" index 85ef0092..fb166986 100644 --- "a/LeetCode/421-430/430. \346\211\201\345\271\263\345\214\226\345\244\232\347\272\247\345\217\214\345\220\221\351\223\276\350\241\250\357\274\210\344\270\255\347\255\211\357\274\211.md" +++ "b/LeetCode/421-430/430. \346\211\201\345\271\263\345\214\226\345\244\232\347\272\247\345\217\214\345\220\221\351\223\276\350\241\250\357\274\210\344\270\255\347\255\211\357\274\211.md" @@ -83,6 +83,48 @@ class Solution { } } ``` +* 时间复杂度:最坏情况下,每个节点会被访问 $h$ 次($h$ 为递归深度,最坏情况下 $h = n$)。整体复杂度为 $O(n^2)$ +* 空间复杂度:最坏情况下所有节点都分布在 `child` 中,此时递归深度为 $n$。复杂度为 $O(n)$ + +--- + +### 递归(优化) + +在上述解法中,由于我们直接使用 `flatten` 作为递归函数,导致递归处理 $head.child$ 后不得不再进行遍历来找当前层的“尾结点”,这导致算法复杂度为 $O(n^2)$。 + +一个可行的优化是,额外设计一个递归函数 `dfs` 用于返回扁平化后的链表“尾结点”,从而确保我们找尾结点的动作不会在每层发生。 + +![image.png](https://pic.leetcode-cn.com/1632439410-oXoxbn-image.png) + +代码: +```Java +class Solution { + public Node flatten(Node head) { + dfs(head); + return head; + } + Node dfs(Node head) { + Node last = head; + while (head != null) { + if (head.child == null) { + last = head; + head = head.next; + } else { + Node tmp = head.next; + Node childLast = dfs(head.child); + head.next = head.child; + head.child.prev = head; + head.child = null; + if (childLast != null) childLast.next = tmp; + if (tmp != null) tmp.prev = childLast; + last = head; + head = childLast; + } + } + return last; + } +} +``` * 时间复杂度:$O(n)$ * 空间复杂度:最坏情况下所有节点都分布在 `child` 中,此时递归深度为 $n$。复杂度为 $O(n)$