题目链接:https://leetcode.cn/problems/permutations/description/
思路:全排列,无重复数字,排列便会有2,1,3这种情况,所以递归无需指定起始点,排列都是从0开始。只不过纵向需要去重,使用一个标记数组,标记好使用过的数即可。
class Solution {
List<List<Integer>> arrayLists = new ArrayList<>();
List<Integer> list = new ArrayList<>();
public List<List<Integer>> permute(int[] nums) {
boolean[] used = new boolean[nums.length];
backTracking(nums, used);
return arrayLists;
}
void backTracking(int[] nums, boolean[] used) {
if (list.size() >= nums.length) {
arrayLists.add(new ArrayList<>(list));
return;
}
for (int i = 0; i < nums.length; i++) {
if (used[i]) continue;
list.add(nums[i]);
used[i] = true;
backTracking(nums, used);
list.remove(list.size()-1);
used[i] = false;
}
}
}
题目链接:https://leetcode.cn/problems/n-queens/
思路:N皇后,也是典型的回溯法,递归树,for是横向棋盘,递归是纵向棋盘,
无非就判断是否可用时复杂一点,涉及到一点剪枝,N皇后要求横向纵向45度和135度都不能出现Q
递归是向下递归的,不符合条件直接回溯了,for迭代,
所以45度和135度只需要判断当前点的左上角方向和右上角方向
List<List<String>> arrayLists = new ArrayList<>();
public List<List<String>> solveNQueens(int n) {
char[][] chars = new char[n][n];
for (char[] c : chars) {
Arrays.fill(c, '.');
}
backTracking(n,0, chars);
return arrayLists;
}
void backTracking(int n, int row, char[][] chars) {
if (row == n) {
List<String> list = new ArrayList<>();
for (char[] aChar : chars) {
list.add(String.valueOf(aChar));
}
arrayLists.add(list);
return;
}
for (int i = 0; i < n; i++) {
if (!isAble(chars, n, row, i)) continue;
chars[row][i] = 'Q';
backTracking(n, row+1,chars);
chars[row][i] = '.';
}
}
boolean isAble(char[][] chars, int n, int x, int y) {
for (int i = 0; i < x; i++) {
if (chars[i][y] == 'Q') return false;
}
for (int i=x-1, j=y-1; i>=0 && j>=0; i--, j--) {
if (chars[i][j] == 'Q') return false;
}
for (int i=x-1, j=y+1; i>=0 && j<n; i--,j++) {
if (chars[i][j] == 'Q') return false;
}
return true;
}
题目链接:https://leetcode.cn/problems/n-queens-ii/
思路:相比上一题更简单也不用记录棋盘结果只需要计数即可。
class Solution {
int count = 0;
public int totalNQueens(int n) {
char[][] chars = new char[n][n];
for (char[] c : chars) {
Arrays.fill(c, '.');
}
backTracking(n,0, chars);
return count;
}
void backTracking(int n, int row, char[][] chars) {
if (row == n) {
count++;
return;
}
for (int i = 0; i < n; i++) {
if (!isAble(chars, n, row, i)) continue;
chars[row][i] = 'Q';
backTracking(n, row+1,chars);
chars[row][i] = '.';
}
}
boolean isAble(char[][] chars, int n, int x, int y) {
for (int i = 0; i < x; i++) {
if (chars[i][y] == 'Q') return false;
}
for (int i=x-1, j=y-1; i>=0 && j>=0; i--, j--) {
if (chars[i][j] == 'Q') return false;
}
for (int i=x-1, j=y+1; i>=0 && j<n; i--,j++) {
if (chars[i][j] == 'Q') return false;
}
return true;
}
}