LeetCode332.重新安排行程
题目链接:332. 重新安排行程 - 力扣(LeetCode)
思路:
class Solution {
public:
//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[result.size() - 1]]) {
if(target.second > 0) {//记录到达机场是否飞过
result.push_back(target.first);
target.second--;
if(backtracking(ticketNum,result)) return true;
result.pop_back();
target.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;
}
};
LeetCode51.N皇后
思路:
class Solution {
public:
vector<vector<string>> result;
void backtracking(int n,int row,vector<string>& chessboard) {
if(row == n) result.push_back(chessboard);//如果遍历到最后一排,则成功
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 < row;i++) {
if(chessboard[i][col] == 'Q') return false;
}
//45度排除
for(int i = row - 1,j = col - 1;i >= 0 && j >= 0; i--,j--) {
if(chessboard[i][j] == 'Q') return false;
}
//135度排除
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) {
vector<string> chessboard(n,string(n,'.'));
backtracking(n,0,chessboard);
return result;
}
};
LeetCode37.解数独
思路:
class Solution {
public:
bool backt(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(backt(board)) return true;//如果找到合适的就立即返回
board[i][j] = '.';//回溯
}
}
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++) {
for(int j = startCol;j < startCol + 3;j++) {
if(board[i][j] == val) return false;
}
}
return true;
}
void solveSudoku(vector<vector<char>>& board) {
backt(board);
}
};