diff --git a/problems/0332.重新安排行程.md b/problems/0332.重新安排行程.md index 395f991e..f7ef8cf7 100644 --- a/problems/0332.重新安排行程.md +++ b/problems/0332.重新安排行程.md @@ -506,6 +506,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数组: