Space complexity : Instead of using a 2D array to represent the chess board, i am using a 1D array , the index of which would represent the row number and the value of arr at row index will be the column number for the correct position of the queen.

i.e

Instead of doing arr[row][col]=1
i am using arr[row]=col ; where queen is positioned at (row,col);

Logic : DFS for every column number ,ranging from 0 to n-1, for all the rows from 0 to n-1 and check the validity of queen position for every row,col combination(using isSafe function)

isSafe function : It checks whether the queen in current position(r,c) is being attacked by any of the r-1 queens positioned in row numbers 0 through r-1.

class Solution {
public:
vector < vector <string> > sol;
int limit;
vector<string> toChessString(vector<int> arr)
{
string s(arr.size(),'.');
vector<string> ans(arr.size(),s);
for(int i=0 ; i<arr.size() ; i++)
ans[i][arr[i]]='Q';
return ans;
}
bool isSafe(vector<int> arr, int r , int c )
{
int check;
for(int row=r-1,ldia=c-1,rdia=c+1 ; row>=0 ; row--,ldia--,rdia++)
{
check=arr[row];
if(check==c || check==ldia || check==rdia)
return false;
}
return true;
}
void solveNqueen(vector<int> arr , int r , int c)
{
if(r==limit)
sol.push_back(toChessString(arr));
else
{
for(int col=c ; col<limit ; col++)
{
arr[r]=col;
if(isSafe(arr,r,col))
solveNqueen(arr,r+1,0);
}
}
}
vector<vector<string> > solveNQueens(int n) {
vector<int> arr(n,0);
limit=n;
solveNqueen(arr,0,0);
return sol;
}
};