From 3635751759fcf689f9baae10ab5fe4a5d642b5f8 Mon Sep 17 00:00:00 2001 From: Steve2020 <841532108@qq.com> Date: Sun, 3 Apr 2022 23:15:06 +0800 Subject: [PATCH] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=EF=BC=880332.=E9=87=8D?= =?UTF-8?q?=E6=96=B0=E5=AE=89=E6=8E=92=E8=A1=8C=E7=A8=8B.md=EF=BC=89?= =?UTF-8?q?=EF=BC=9A=E5=A2=9E=E5=8A=A0typescript=E7=89=88=E6=9C=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0332.重新安排行程.md | 44 +++++++++++++++++++++++++++++ 1 file changed, 44 insertions(+) diff --git a/problems/0332.重新安排行程.md b/problems/0332.重新安排行程.md index 01f81c4d..370db45b 100644 --- a/problems/0332.重新安排行程.md +++ b/problems/0332.重新安排行程.md @@ -448,6 +448,50 @@ var findItinerary = function(tickets) { ``` +### TypeScript + +```typescript +function findItinerary(tickets: string[][]): string[] { + /** + TicketsMap 实例: + { NRT: Map(1) { 'JFK' => 1 }, JFK: Map(2) { 'KUL' => 1, 'NRT' => 1 } } + 这里选择Map数据结构的原因是:与Object类型的一个主要差异是,Map实例会维护键值对的插入顺序。 + */ + type TicketsMap = { + [index: string]: Map + }; + tickets.sort((a, b) => { + return a[1] < b[1] ? -1 : 1; + }); + const ticketMap: TicketsMap = {}; + for (const [from, to] of tickets) { + if (ticketMap[from] === undefined) { + ticketMap[from] = new Map(); + } + ticketMap[from].set(to, (ticketMap[from].get(to) || 0) + 1); + } + const resRoute = ['JFK']; + backTracking(tickets.length, ticketMap, resRoute); + return resRoute; + function backTracking(ticketNum: number, ticketMap: TicketsMap, route: string[]): boolean { + if (route.length === ticketNum + 1) return true; + const targetMap = ticketMap[route[route.length - 1]]; + if (targetMap !== undefined) { + for (const [to, count] of targetMap.entries()) { + if (count > 0) { + route.push(to); + targetMap.set(to, count - 1); + if (backTracking(ticketNum, ticketMap, route) === true) return true; + targetMap.set(to, count); + route.pop(); + } + } + } + return false; + } +}; +``` + ### Swift 直接迭代tickets数组: