题型模板
result = []
def backtrack(路径, 选择列表):
if 满足结束条件:
result.add(路径)
return
for 选择 in 选择列表:
做选择
backtrack(路径, 选择列表)
撤销选择
复制代码
全排列
给定一个 没有重复 数字的序列,返回其所有可能的全排列。
复制代码
List<List<Integer>> res = new ArrayList<>();
public List<List<Integer>> permute(int[] nums) {
LinkedList<Integer> temp = new LinkedList<>();
backtrack(nums,temp);
return res;
}
private void backtrack(int[] nums, LinkedList<Integer> temp) {
if(temp.size()==nums.length){
res.add(new LinkedList(temp));
return;
}
for (int i = 0; i < nums.length; i++) {
if(temp.contains(nums[i])){
continue;
}
temp.add(nums[i]);
backtrack(nums,temp);
temp.removeLast();
}
}
复制代码
N皇后
List<List<String>> res;
public List<List<String>> solveNQueens(int n) {
if (n <= 0) return null;
res = new LinkedList<>();
char[][] board = new char[n][n];
for (char[] chars : board) Arrays.fill(chars, '.');
backtrack(board, 0);
return res;
}
private void backtrack(char[][] board, int row) {
if (row == board.length) {
res.add(charToString(board));
return;
}
int n = board[row].length;
for (int col = 0; col < n; col++) {
if (!isValid(board, row, col)) continue;
board[row][col] = 'Q';
backtrack(board, row + 1);
board[row][col] = '.';
}
}
private boolean isValid(char[][] board, int row, int col) {
int rows = board.length;
for (char[] chars : board) if (chars[col] == 'Q') return false;
for (int i = row - 1, j = col + 1; i >= 0 && j < rows; 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;
}
复制代码