思路
python可以使用調庫法,使用深度拷貝
"""
# Definition for a Node.
class Node:def __init__(self, x: int, next: 'Node' = None, random: 'Node' = None):self.val = int(x)self.next = nextself.random = random
"""class Solution:def copyRandomList(self, head: 'Optional[Node]') -> 'Optional[Node]':return copy.deepcopy(head)
此外,新的想法就是我們采用字典去存儲原節點—>復制后新的節點的映射關系
class Solution:def __init__(self):self.cached_node = {} #這個字典用于存儲 原節點 -> 復制后的新節點 的映射關系。def copyRandomList(self, head: 'Optional[Node]') -> 'Optional[Node]':if head is None:return Noneif head not in self.cached_node:new_node = Node(head.val)self.cached_node[head] = new_nodenew_node.next = self.copyRandomList(head.next)new_node.random = self.copyRandomList(head.random)return self.cached_node[head]