又是一道拓扑排序的变形题, Given org = [1,2,3], seqs = [[1,2],[1,3]]
给一串序列看后面能否组成这个序列。
思路:拓扑排序的题就要记录邻接矩阵,然后和每个点的入度。入度为0放入队列,然后取出队列里的值,让它的邻居入度都减1,如果入度为0的点继续放在队列里,依次循环。因为拓扑排序是任意输出一组结果,但这里要求结果是唯一的。要求不能同时出现两个入度为0的点放入队列。所以我们可以设计一个level值来记录bfs的层数。有点像树的层级输出,并且分层放置。这里面还得加一个node的set, 来存放seqs里面的所有node,最后判断true or false就是判断是否生成的序列和原序列一致,是否node的个数和原序列一致,level长度和原序列是否一致。
python代码:
class Solution:
"""
@param org: a permutation of the integers from 1 to n
@param seqs: a list of sequences
@return: true if it can be reconstructed only one or false
"""
def sequenceReconstruction(self, org, seqs):
# write your code here
from collections import deque
neighbor = {}
indegree = {}
nodes = set()
for i in org:
neighbor[i] = []
indegree[i] = 0
for pair in seqs:
nodes = nodes | set(pair)
for i in range(len(pair) - 1):
if pair[i] not in neighbor or pair[i+1] not in neighbor:
return False
neighbor[pair[i]].append(pair[i+1])
indegree[pair[i+1]] += 1
queue = deque()
level = 0
res = []
for key in indegree:
if indegree[key] == 0:
queue.append(key)
while queue:
size = len(queue)
level += 1
for _ in range(size):
node = queue.popleft()
res.append(node)
for i in neighbor[node]:
indegree[i] -= 1
if indegree[i] == 0:
queue.append(i)
return res == org and len(nodes) == len(org) and level == len(org)
网友评论