明天就是大年三十了,首先祝各位朋友新年快乐,新春愉快!巧合的是,今天正好是回溯章节的收尾,这也是辞旧迎新的好兆头。
第一题是重新安排行程https://leetcode.cn/problems/reconstruct-itinerary/description/,一道难题,确实有点超出自己的能力就看看题解抄一遍代码ac了。相当于抄了一遍答案哈哈
class Solution {
public: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>& targets : targets[result[result.size() - 1]]){if (targets.second > 0){result.push_back(targets.first);targets.second--;if (backtracking(ticketNum, result)) return true;result.pop_back();targets.second++;}}return false;}vector<string> findItinerary(vector<vector<string>>& tickets) {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皇后问题https://leetcode.cn/problems/n-queens/description/,直接上卡哥题解。思路并不难懂,通过每行遍历,将列依次放入皇后,向下一行递归,并调用isValid函数判断合法性,若当前位置合法,则放入皇后。
class Solution {
public:vector<vector<string>> result;void backtracking(int n, int row, vector<string>& chessboard){if (row == n){result.push_back(chessboard);return;}for (int col = 0; col < n; col++){if (isValid(row, col, chessboard, n)){chessboard[row][col] = 'Q';backtracking(n, row + 1, chessboard);chessboard[row][col] = '.';}}}bool isValid(int row, int col, vector<string>& chessboard, int n){for (int i = 0; i < n; 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; i--, j++){if (chessboard[i][j] == 'Q') return false;}return true;}vector<vector<string>> solveNQueens(int n) {std::vector<std::string> chessboard(n, std::string(n, '.'));backtracking(n, 0, chessboard);return result;}
};
第三题是解数独https://leetcode.cn/problems/sudoku-solver/,作为回溯章节的压轴题,与其他题目最大的不同就是该题需要两个for循环确定一个点。
class Solution {
public: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] != '.') continue;for (char k = '1'; k <= '9'; k++){if (isValid(i, j, k, board)){board[i][j] = k;if(backtracking(board)) return true;board[i][j] = '.';}}return false;}}return true;}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++){for (int j = startCol; j < startCol + 3; j++){if (board[i][j] == val) return false;}}return true;}void solveSudoku(vector<vector<char>>& board) {backtracking(board);}
};
刷完了回溯,给我的感觉是回溯像一个已经有框架的楼房,只需要在某些部分上添加东西。