"""
key is to store tickets information in default dictionary in lexical order.
and what to do when ran into destination before going through all tickets.
if encounter destination, add to result list first.
then reverse the result in the end.
"""
iterative solution
class Solution(object):
def findItinerary(self, tickets):
"""
:type tickets: List[List[str]]
:rtype: List[str]
"""
targets=collections.defaultdict(list)
for a , b in sorted(tickets)[::-1]:
targets[a]+=[b]
#print targets
route =[]
stack=['JFK']
while stack:
while targets[stack[-1]]:
stack.append(targets[stack[-1]].pop())
route.append(stack.pop())
return route[::-1]
recursive solution
class Solution(object):
def findItinerary(self, tickets):
"""
:type tickets: List[List[str]]
:rtype: List[str]
"""
targets=collections.defaultdict(list)
for a , b in sorted(tickets)[::-1]:
targets[a]+=[b]
#print targets
route =[]
def visit(airport):
while targets[airport]:
visit(targets[airport].pop())
route.append(airport)
visit('JFK')
return route[::-1]
332. Reconstruct Itinerary
最后编辑于 :
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。
推荐阅读更多精彩内容
- 这题做了一天。。一天。。上午拿到之后感觉挺easy的,我想像NQueens那样先DFS找到所有的解。结果怎么也无法...
- 把每个机场视为一个节点,一张机票视为连接两个机场节点的有向边,这道题实际上是求一个有向图的一笔画问题,即从一个确定...
- Given a list of airline tickets represented by pairs of d...