题目
Check whether the original sequence org can be uniquely reconstructed from the sequences in seqs. The org sequence is a permutation of the integers from 1 to n, with 1 ≤ n ≤ 10^4. Reconstruction means building a shortest common supersequence of the sequences in seqs (i.e., a shortest sequence so that all sequences in seqs are subsequences of it). Determine whether there is only one sequence that can be reconstructed from seqs and it is the org sequence.
Example
Example 1:
Input:org = [1,2,3], seqs = [[1,2],[1,3]]
Output: false
Explanation:
[1,2,3] is not the only one sequence that can be reconstructed, because [1,3,2] is also a valid sequence that can be reconstructed.
Example 2:
Input: org = [1,2,3], seqs = [[1,2]]
Output: false
Explanation:
The reconstructed sequence can only be [1,2].
Example 3:
Input: org = [1,2,3], seqs = [[1,2],[1,3],[2,3]]
Output: true
Explanation:
The sequences [1,2], [1,3], and [2,3] can uniquely reconstruct the original sequence [1,2,3].
Example 4:
Input:org = [4,1,5,2,6,3], seqs = [[5,2,6,3],[4,1,5,2]]
Output:true
我的想法
甚至都不知道为什么这道题可以用BFS做。。。。其实当知道这个题是用BFS之后,有想到应该和Topological Sorting相关,但是没有理明白
解答
jiuzhang solution:
public class Solution {
public boolean sequenceReconstruction(int[] org, int[][] seqs) {
Map<Integer, Set<Integer>> map = new HashMap<Integer, Set<Integer>>();
Map<Integer, Integer> indegree = new HashMap<Integer, Integer>();
for (int num : org) {
map.put(num, new HashSet<Integer>());
indegree.put(num, 0);
}
//calculate indegree of nodes in each seq
int n = org.length;
int count = 0;
for (int[] seq : seqs) {
count += seq.length;
//org is a permutation of 1-n, so there is no possibility
//that seq[i] could smaller than 1 or bigger than n
if (seq.length >= 1 && (seq[0] <= 0 || seq[0] > n))
return false;
for (int i = 1; i < seq.length; i++) {
if (seq[i] <= 0 || seq[i] > n)
return false;
//HashSet.add(e) will return true if the set did not
//already contain e
if (map.get(seq[i - 1]).add(seq[i]))
indegree.put(seq[i], indegree.get(seq[i]) + 1);
}
}
// case: [1], []
if (count < n)
return false;
//add 0 indegree nodes to the queue
Queue<Integer> q = new ArrayDeque<Integer>();
for (int key : indegree.keySet())
if (indegree.get(key) == 0)
q.add(key);
//topological sorting
int cnt = 0;
while (q.size() == 1) {
int ele = q.poll();
for (int next : map.get(ele)) {
indegree.put(next, indegree.get(next) - 1);
if (indegree.get(next) == 0) q.add(next);
}
if (ele != org[cnt]) {
return false;
}
cnt++;
}
return cnt == org.length;
}
}