回溯part06
写了好长时间,最后超时了qaq
/**
* @param {string[][]} tickets
* @return {string[]}
*/
//ticket[1] = [2,3]表示航线1是从地点2飞到地点3的
//所有机票必须用过一次
//优先选取字典排序更小的行程
var findItinerary = function(tickets) {
let res = [];
let used = new Array(tickets.length).fill(0);
backtracking(tickets, ["JFK"], 0,res, "JFK", used);
return res[0];
};
//cn记录已经使用的机票的个数
function backtracking(tickets, path, cn, res, from,used) {
//边界条件
if(cn === tickets.length){
if(res.length == 0){
console.log('第一个',path);
res.push([...path]);
return;
}
if(res.length == 1){
for(let j = 0; j < path.length; j++){
if(res[0][j] != path[j]){
if(res[0][j] < path[j]) return;
console.log('比阿胶',res);
console.log(path);
console.log('---------------');
res.pop();
res.push([...path]);
return;
}
}
}
}
//选择使用哪一个tiket
for(let i = 0; i < tickets.length; i++){
//如果起飞地不是指定的from,直接跳过
if(tickets[i][0] != from) continue;
if(used[i]) continue;
used[i] = true;
path.push(tickets[i][1]);
backtracking(tickets, path, cn + 1, res, tickets[i][1], used);
path.pop();
used[i] = false;
}
}