leetcode 332 飞机行程
private static boolean backTracking2(int len) {
if(res.size()== len+1){
return true;
}
String last = res.getLast();
if(map.containsKey(last)){
for(Map.Entry<String,Integer> target:map.get(last).entrySet()){
int cnt = target.getValue();
if(cnt>0){
res.offer(target.getKey());
target.setValue(cnt-1);
if(backTracking2(len))
return true; // 递归函数boolean返回类型,因为找到一条最优的就可以返回了
res.pollLast();
target.setValue(cnt);
}
}
}
return false;
}
leetcode 51 N皇后
拆分小步就看起来也不难
private static void backTracking(int n, int row,char[][] chess) {
if(row==chess.length) {
result.add(array2List(chess));// 拆出来一个二维数组转list函数
return;
}
for(int i=0;i<n;i++){
if(isValid(chess,row,i)) { // 拆出来一个valid函数
chess[row][i] = 'Q';
backTracking(n, row + 1, chess);
chess[row][i]='.'; // 当回溯
}
}
}
leetcode 37 数独
有点难,还没做,待补充