我正在嘗試解決這個 nQueens 問題,我的代碼如下所示:
class Solution {
public:
vector<vector<string>> ans;
bool canPlace(vector<string> &board, int row, int col, int n){
//upper left diagonal
int rowIndex = row;
int colIndex = col;
while(rowIndex >= 0 and colIndex >= 0){
if(board[rowIndex][colIndex] == 'Q'){
return false;
}
rowIndex--;
colIndex--;
}
// left side
rowIndex = row;
colIndex = col;
while(colIndex >= 0){
if(board[rowIndex][colIndex] == 'Q'){
return false;
}
colIndex--;
}
// left side
rowIndex = row;
colIndex = col;
while(rowIndex < n and colIndex >= 0){
if(board[rowIndex][colIndex] == 'Q'){
return false;
}
rowIndex ;
colIndex--;
}
return true;
}
void nQueens(vector<string> &board, int col, int n){
if(col == n){
ans.push_back(board);
for(int i = 0; i < n; i ){
cout<<board[i]<<", ";
}
cout<<endl;
return;
}
for(int row = 0; row < n; row ){
if(canPlace(board, row, col, n)){
cout<<"Changing board from: "<<board[row][col]<<endl;
board[row][col] = 'Q';
nQueens(board, col 1,n);
board[row][col] = '.';
}
}
}
vector<vector<string>> solveNQueens(int n) {
vector<string> board(n);
string s(n, '.');
for(int i = 0; i < n; i ){
board[i] = s;
// push_back gives weird result
}
nQueens(board, 0, n);
return ans;
}
};
在最后一個 solveNQueens 函式中。在 for 回圈中,如果我使用board.push_back(s)而不是board[i] = s,leetcode 會拋出錯誤答案錯誤,并且使用 cout 時的輸出會顯示奇怪的隨機符號。為什么是這樣?push_back 不應該給出相同的結果嗎?我很想知道為什么會發生這種情況。
這是 leetcode 問題的鏈接:https ://leetcode.com/problems/n-queens
uj5u.com熱心網友回復:
vector<string> board(n);
用n元素填充向量。如果你現在添加額外的!元素push_back,您有一個包含兩倍元素的向量。前半部分已經從建構式中輸入std::vector,下半部分稍后推送。
如果使用默認建構式
vector<string> board;
與 結合使用push_back,您將獲得與示例代碼相同的結果。
對于大型向量,預先初始化n元素和訪問 via的解決方案operator[]可以快得多,因為不需要在向量內部進行重新分配和復制操作。如果速度很重要:測量!
uj5u.com熱心網友回復:
push_back在向量的末尾添加一個新元素,將其大小增加 1。
賦值不會這樣做;它復制/移動值(在您的情況下i在板的那個位置vector)。
她們不一樣。
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/349064.html
下一篇:磚在墻上的排列方式共有多少種?
