mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-07 15:45:40 +08:00
Merge pull request #1199 from xiaofei-2020/back19
添加(0332.重新安排行程.md):增加typescript版本
This commit is contained in:
@ -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<string, number>
|
||||||
|
};
|
||||||
|
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
|
### Swift
|
||||||
|
|
||||||
直接迭代tickets数组:
|
直接迭代tickets数组:
|
||||||
|
Reference in New Issue
Block a user