59、分割回文串
给你一个字符串 s,请你将 s 分割成一些 子串,使每个子串都是 回文串 。返回 s 所有可能的分割方案。
示例 1:
输入:s = "aab"
输出:[["a","a","b"],["aa","b"]]
示例 2:
输入:s = "a"
输出:[["a"]]
class Solution {
List<List<String>> result = new ArrayList<>(); // 存放最终结果
List<String> path = new ArrayList<>(); // 存放当前路径(一个切割方案)
public List<List<String>> partition(String s) {
backtrack(s, 0); // 从第0个字符开始回溯
return result;
}
// 回溯函数:start 表示当前起始下标
private void backtrack(String s, int start) {
// 如果已经切到字符串末尾,说明找到了一种切法
if (start == s.length()) {
result.add(new ArrayList<>(path)); // 加入结果集
return;
}
// 枚举所有可能的切割位置
for (int end = start; end < s.length(); end++) {
String substring = s.substring(start, end + 1);
// 如果当前子串是回文串,就加入路径中
if (isPalindrome(substring)) {
path.add(substring); // 做选择
backtrack(s, end + 1); // 继续往后切
path.remove(path.size() - 1); // 撤销选择(回溯)
}
}
}
// 判断一个字符串是否是回文串
private boolean isPalindrome(String str) {
int left = 0, right = str.length() - 1;
while (left < right) {
if (str.charAt(left) != str.charAt(right)) return false;
left++;
right--;
}
return true;
}
}
60、N皇后

public class Solution {
public List<List<String>> solveNQueens(int n) {
List<List<String>> res = new ArrayList<>();
char[][] board = new char[n][n];
// 初始化棋盘,全是 '.'
for (int i = 0; i < n; i++) {
Arrays.fill(board[i], '.');
}
// 三个集合,分别记录列、两个方向的对角线是否被占用
Set<Integer> columns = new HashSet<>();
Set<Integer> diag1 = new HashSet<>(); // row - col
Set<Integer> diag2 = new HashSet<>(); // row + col
backtrack(0, n, board, columns, diag1, diag2, res);
return res;
}
private void backtrack(int row, int n, char[][] board,
Set<Integer> columns, Set<Integer> diag1, Set<Integer> diag2,
List<List<String>> res) {
if (row == n) {
// 收集结果
List<String> solution = new ArrayList<>();
for (char[] line : board) {
solution.add(new String(line));
}
res.add(solution);
return;
}
for (int col = 0; col < n; col++) {
if (columns.contains(col) || diag1.contains(row - col) || diag2.contains(row + col)) {
continue;
}
// 放皇后
board[row][col] = 'Q';
columns.add(col);
diag1.add(row - col);
diag2.add(row + col);
backtrack(row + 1, n, board, columns, diag1, diag2, res);
// 回溯
board[row][col] = '.';
columns.remove(col);
diag1.remove(row - col);
diag2.remove(row + col);
}
}
}
|
作者:万能包哥 出处:http://www.cnblogs.com/mybloger/ 本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。 如果文中有什么错误,欢迎指出。以免更多的人被误导。 |
浙公网安备 33010602011771号