@@ -506,6 +506,50 @@ var findItinerary = function(tickets) {
506506
507507```
508508
509+ ### TypeScript
510+
511+ ``` typescript
512+ function findItinerary(tickets : string [][]): string [] {
513+ /**
514+ TicketsMap 实例:
515+ { NRT: Map(1) { 'JFK' => 1 }, JFK: Map(2) { 'KUL' => 1, 'NRT' => 1 } }
516+ 这里选择Map数据结构的原因是:与Object类型的一个主要差异是,Map实例会维护键值对的插入顺序。
517+ */
518+ type TicketsMap = {
519+ [index : string ]: Map <string , number >
520+ };
521+ tickets .sort ((a , b ) => {
522+ return a [1 ] < b [1 ] ? - 1 : 1 ;
523+ });
524+ const ticketMap: TicketsMap = {};
525+ for (const [from, to] of tickets ) {
526+ if (ticketMap [from ] === undefined ) {
527+ ticketMap [from ] = new Map ();
528+ }
529+ ticketMap [from ].set (to , (ticketMap [from ].get (to ) || 0 ) + 1 );
530+ }
531+ const resRoute = [' JFK' ];
532+ backTracking (tickets .length , ticketMap , resRoute );
533+ return resRoute ;
534+ function backTracking(ticketNum : number , ticketMap : TicketsMap , route : string []): boolean {
535+ if (route .length === ticketNum + 1 ) return true ;
536+ const targetMap = ticketMap [route [route .length - 1 ]];
537+ if (targetMap !== undefined ) {
538+ for (const [to, count] of targetMap .entries ()) {
539+ if (count > 0 ) {
540+ route .push (to );
541+ targetMap .set (to , count - 1 );
542+ if (backTracking (ticketNum , ticketMap , route ) === true ) return true ;
543+ targetMap .set (to , count );
544+ route .pop ();
545+ }
546+ }
547+ }
548+ return false ;
549+ }
550+ };
551+ ```
552+
509553### Swift
510554
511555直接迭代tickets数组:
0 commit comments