concept
Backtracking is actually a similar attempt to enumerate the search process, the main problem is to find a solution in search attempt process, when found to have been solved condition is not satisfied, on the "back" to return to try a different path.
Key Words and Phrases
Solution space tree, tree, DFS
Fake code
= Result [] DEF BackTrack (path selection list): IF the end of the condition result.add (path) return for selection in the selection list to choose // corresponds to a preorder traversal of a binary tree BackTrack (path selection list) deselection / / after the sequence corresponding to the binary tree traversal
Tree traversal void Traverse (the TreeNode the root) { for (the TreeNode Child: root.childern) // preorder traversal desired operating Traverse (Child); // operations required postorder }
Classic examples
Full array
package backtracing; import java.util.ArrayList; import java.util.List; // 求n的全排列 public class PermutePrac { private List<List<Integer>> listList = new ArrayList<>(); public List<List<Integer>> permute(int[] nums) { int len = nums.length; backTrack(new ArrayList<>(), len, nums); return listList; } public void backTrack(List<Integer> list, int n, int[] nums) { // 判断回溯值 if (list.size() == n) { listList.add(new ArrayList<>(list)); } // 遍历 for (int i = 0; i < n; i++) { // 约束条件 if (list.contains(nums[i])) { continue; } list.add(nums[i]); backTrack(list, n, nums); // 回溯 list.remove(list.size() - 1); } } }
Eight Queens
Package backtracing.nqueen; Import of java.util.ArrayList; Import java.util.List; // leetcode 51 is // // Given an integer n, returns all of the different solutions queens problem n. // // Each solution contains an explicit n pieces placed queens problem program, which the 'Q' and '' and a gap representing the queen. // // Example: // // Input: 4 // Output: [ // [ ".Q ..", // Solution. 1 // "Q ...", // "Q ...", // "..Q."], // // [ "..Q.", // Method 2 // "Q ...", // ".Q.."] // ] public class Solution { List<List<String>> listlist = new ArrayList<>(); public List<List<String>> solveNQueens(int n) { solveNQueenUtil(0, n, new ArrayList<>()); return listlist; } private void solveNQueenUtil(int row, int n, List<String> list) { if (row == n) { listlist.add(new ArrayList<>(list)); return; } for (int col = 0; col < n; col++) { list.add(generateColn(col, n)); if (isSafe(list, n)) { solveNQueenUtil(row + 1, n, list); } list.remove(list.size() - 1); } } private String generateColn(int col, int n) { StringBuffer sb = new StringBuffer(); for (int i = 0; i < n; i++) { if (i == col) { sb.append("Q"); } else { sb.append("."); } } return sb.toString(); } boolean isSafe(List<String> list, int n) { return isColSafe(list, n) && isLeftDiagnoseSafe(list, n) && isRightDiagnoseSafe(list, n); } boolean isColSafe(List<String> list, int n) { for (int col = 0; col < n; col++) { int count = 0; for (int row = 0; row < list.size(); row++) { if (list.get(row).charAt(col) == 'Q') { count++; } } if (count > 1) { return false; } } return true; } boolean isLeftDiagnoseSafe(List<String> list, int n) { for (int col = 0; col < n; col++) { int nextRow = 0; int nextCol = col; int count = 0; if (leftDianoseUtil(list, nextRow, nextCol, count)) return false; } for (int row = 0; row < list.size(); row++) { int nextRow = row; int nextCol = n - 1; int count = 0; if (leftDianoseUtil(list, nextRow, nextCol, count)) return false; } return true; } private boolean leftDianoseUtil(List<String> list, int nextRow, int nextCol, int count) { while (nextRow < list.size() && nextCol >= 0) { if (list.get(nextRow).charAt(nextCol) == 'Q') { count++; } nextCol--; nextRow++; } if (count > 1) { return true; } return false; } boolean isRightDiagnoseSafe(List<String> list, int n) { for (int col = n - 1; col >= 0; col--) { int nextRow = 0; int nextCol = col; int count = 0; if (rightDianoseUtil(list, n, nextRow, nextCol, count)) return false; } for (int row = 0; row < list.size(); row++) { int nextRow = row; int nextCol = 0; int count = 0; if (rightDianoseUtil(list, n, nextRow, nextCol, count)) return false; } return true; } private boolean rightDianoseUtil(List<String> list, int n, int nextRow, int nextCol, int count) { while (nextRow < list.size() && nextCol < n) { if (list.get(nextRow).charAt(nextCol) == 'Q') { count++; } nextCol++; nextRow++; } if (count > 1) { return true; } return false; } public static void main(String[] args) { Solution solution = new Solution(); solution.solveNQueens(4); System.out.println(solution.listlist); } }
References:
1. https://leetcode-cn.com/problems/n-queens/solution/hui-su-suan-fa-xiang-jie-by-labuladong/ (primary reference)
2. https://leetcode-cn.com/problems/n-queens/solution/nhuang-hou-by-leetcode/