第一题 重新安排里程
class Solution {
private:
// unordered_map<出发机场, map<到达机场, 航班次数>> targets
unordered_map<string, map<string, int>> targets;
bool backtracking(int ticketNum, vector<string>& result) {
if (result.size() == ticketNum + 1) {
return true;
}
for (pair<const string, int>& target : targets[result.back()]) {
if (target.second > 0 ) { // 记录到达机场是否飞过了
result.push_back(target.first);
target.second--;
if (backtracking(ticketNum, result)) return true;
result.pop_back();
target.second++;
}
}
return false;
}
public:
vector<string> findItinerary(vector<vector<string>>& tickets) {
targets.clear();
vector<string> result;
for (const vector<string>& vec : tickets) {
targets[vec[0]][vec[1]]++; // 记录映射关系
}
result.push_back("JFK"); // 起始机场
backtracking(tickets.size(), result);
return result;
}
};
第二题N皇后
class Solution {
private:
vector<vector<string>> result;
bool isvalid(int row, int col,int n ,vector<string> &chessboard){
for(int i = 0;i < row ; i++){
if(chessboard[i][col] == 'Q'){
return false;
}
}
for(int i = row - 1,j = col - 1;i >= 0 && j >= 0; i-- , j--){
if(chessboard[i][j] == 'Q'){
return false;
}
}
for(int i = row - 1,j = col + 1; i >= 0 && j <= n - 1 ; i-- , j++){
if(chessboard[i][j] == 'Q'){
return false;
}
}
return true;
};
void backtrack(vector<string> &chessboard,int row ,int n){
if(row == n ) {
result.push_back(chessboard);
return;
}
for(int col = 0;col < n ;col++){
if(isvalid(row,col,n,chessboard)){
chessboard[row][col] ='Q';
backtrack(chessboard,row + 1,n);
chessboard[row][col] ='.';
}
}
return;
};
public:
vector<vector<string>> solveNQueens(int n) {
vector<string> chessboard(n,string(n,'.'));
backtrack(chessboard,0,n);
return result;
}
};
第三题 解数独
class Solution {
private:
bool backtracking(vector<vector<char>>& board) {
for (int i = 0; i < board.size(); i++) { // 遍历行
for (int j = 0; j < board[0].size(); j++) { // 遍历列
if (board[i][j] == '.') {
for (char k = '1'; k <= '9'; k++) { // (i, j) 这个位置放k是否合适
if (isValid(i, j, k, board)) {
board[i][j] = k; // 放置k
if (backtracking(board)) return true; // 如果找到合适一组立刻返回
board[i][j] = '.'; // 回溯,撤销k
}
}
return false; // 9个数都试完了,都不行,那么就返回false
}
}
}
return true; // 遍历完没有返回false,说明找到了合适棋盘位置了
}
bool isValid(int row, int col, char val, vector<vector<char>>& board) {
for (int i = 0; i < 9; i++) { // 判断行里是否重复
if (board[row][i] == val) {
return false;
}
}
for (int j = 0; j < 9; j++) { // 判断列里是否重复
if (board[j][col] == val) {
return false;
}
}
int startRow = (row / 3) * 3;
int startCol = (col / 3) * 3;
for (int i = startRow; i < startRow + 3; i++) { // 判断9方格里是否重复
for (int j = startCol; j < startCol + 3; j++) {
if (board[i][j] == val ) {
return false;
}
}
}
return true;
}
public:
void solveSudoku(vector<vector<char>>& board) {
backtracking(board);
}
};