代码随想录算法刷题训练营day30:LeetCode(332)重新安排行程、LeetCode(51)n-皇后、LeetCode(37)解数独
LeetCode(332)重新安排行程
题目
代码
//第二次刷题---在刷--高难度---注意超时---该代码照着代码随想录卡哥编写的代码写的,题目难度过大,目前解决不了
/* 该方法是对第二个方法的改进,主要变化在于将某点的所有终点变更为链表的形式,优点在于
1.添加终点时直接在对应位置添加节点,避免了TreeMap增元素时的频繁调整
2.同时每次对终点进行增加删除查找时直接通过下标操作,避免hashMap反复计算hash*/
class Solution {
private Deque<String> res;
private Map<String, Map<String, Integer>> map;
private boolean backTracking(int ticketNum){
if(res.size() == ticketNum + 1){
return true;
}
String last = res.getLast();
if(map.containsKey(last)){
//防止出现null
for(Map.Entry<String, Integer> target : map.get(last).entrySet()){
int count = target.getValue();
if(count > 0){
res.add(target.getKey());
target.setValue(count - 1);
if(backTracking(ticketNum)) return true;
res.removeLast();
target.setValue(count);
}
}
}
return false;
}
public List<String>