目录
332 重新安排行程
class Solution {
public:
unordered_map<string, map<string, int>> target;
bool backtracking(int ticketNum, vector<string>& result){
if(result.size() == ticketNum + 1){
return true;
}
for(pair<const string, int>& m : target[result[result.size()-1]]){
if(m.second > 0){
m.second--;
result.push_back(m.first);
if(backtracking(ticketNum, result)) return true;
m.second++;
result.pop_back();
}
}
return false;
}
vector<string> findItinerary(vector<vector<string>>& tickets) {
vector<string> result;
for(vector<string>& v : tickets){
target[v[0]][v[1]]++;
}
result.push_back("JFK");
backtracking(tickets.size(), result);
return result;
}
};
51 N皇后
class Solution {
public:
vector<vector<string>> result;
void backtracking(vector<string>& chessboard, int n, int row){
if(row == n){
result.push_back(chessboard);
return;
}
for(int i = 0; i < n; i++){
if(isvaild(chessboard, row, i)){
chessboard[row][i] = 'Q';
backtracking(chessboard, n, row+1);
chessboard[row][i] = '.';
}
}
}
bool isvaild(vector<string>& chessboard, int row, int column){
for(int j = 0; j < row; j++){
if(chessboard[j][column] == 'Q'){
return false;
}
}
for(int i = row-1, j = column-1; i >= 0 && j >= 0; i--, j--){
if(chessboard[i][j] == 'Q'){
return false;
}
}
for(int i = row-1, j = column+1; i >= 0 && j < chessboard.size(); i--, j++){
if(chessboard[i][j] == 'Q'){
return false;
}
}
return true;
}
vector<vector<string>> solveNQueens(int n) {
vector<string> chessboard(n, string(n, '.'));
result.clear();
backtracking(chessboard, n, 0);
return result;
}
};
37 解数独
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] == '.'){
for(char num = '1'; num <= '9'; num++){
if(isvaild(i, j, num, board)){
board[i][j] = num;
bool result = backtracking(board);
if(result == true) { return true; }
board[i][j] = '.';
}
}
return false;
}
}
}
return true;
}
bool isvaild(int row, int col, int num, vector<vector<char>>& board){
for(int i = 0; i < board.size(); i++){
if(board[i][col] == num){
return false;
}
}
for(int j = 0; j < board.size(); j++){
if(board[row][j] == num){
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] == num){
return false;
}
}
}
return true;
}
void solveSudoku(vector<vector<char>>& board) {
backtracking(board);
}
};