Basic BackTrack Frame
1 2 3 4 5 6 7 8 9 10
| result = [] def backtrack(路径, 选择列表): if 满足结束条件: result.add(路径) return
for 选择 in 选择列表: 做选择 backtrack(路径, 选择列表) 撤销选择
|
Full Permutation
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32
| List<List<Integer>> res = new LinkedList<>();
List<List<Integer>> permute(int[] nums) { LinkedList<Integer> track = new LinkedList<>(); backtrack(nums, track); return res; }
void backtrack(int[] nums, LinkedList<Integer> track) { if (track.size() == nums.length) { res.add(new LinkedList(track)); return; }
for (int i = 0; i < nums.length; i++) { if (track.contains(nums[i])) continue; track.add(nums[i]); backtrack(nums, track); track.removeLast(); } }
|
Queen
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56
| vector<vector<string>> res;
vector<vector<string>> solveNQueens(int n) { vector<string> board(n, string(n, '.')); backtrack(board, 0); return res; }
void backtrack(vector<string>& board, int row) { if (row == board.size()) { res.push_back(board); return; }
int n = board[row].size(); for (int col = 0; col < n; col++) { if (!isValid(board, row, col)) continue; board[row][col] = 'Q'; backtrack(board, row + 1); board[row][col] = '.'; } }
bool isValid(vector<string>& board, int row, int col) { int n = board.size(); for (int i = 0; i < n; i++) { if (board[i][col] == 'Q') return false; } for (int i = row - 1, j = col + 1; i >= 0 && j < n; i--, j++) { if (board[i][j] == 'Q') return false; } for (int i = row - 1, j = col - 1; i >= 0 && j >= 0; i--, j--) { if (board[i][j] == 'Q') return false; } return true; }
|
If we just want to find one answer, just return the result when reach the goal:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
| bool backtrack(vector<string>& board, int row) { if (row == board.size()) { res.push_back(board); return true; } ... for (int col = 0; col < n; col++) { ... board[row][col] = 'Q';
if (backtrack(board, row + 1)) return true;
board[row][col] = '.'; }
return false; }
|