标签:
还是思维不够清晰,试了好多次才试对,代码里注释掉的部分复杂度太高,不能通过。
class Solution { private: vector<vector<string>> res; public: bool isLegal(vector<string> &temp, int row, int col) { //列 for(int i = 0; i < row; i++) if(temp[i][col] == ‘Q‘)return false; //右对角线 for(int i = row-1, j=col-1; i >= 0 && j >= 0; i--,j--) if(temp[i][j] == ‘Q‘)return false; //左对角线 for(int i = row-1, j=col+1; i >= 0 && j < temp.size(); i--,j++) if(temp[i][j] == ‘Q‘)return false; return true; } /* bool isLegal(vector<string> &temp,int H,int W) { for(int j=0;j<H;j++) for(int i=0;i<=W;i++) { if(temp[j][i]==‘Q‘&&(abs(j-H)==abs(i-W)||i==W)) return false; } return true; }*/ void procedure(vector<string> &temp,int rows) { if(rows==temp.size()) { res.push_back(temp); return; } for(int cols=0;cols<temp.size();cols++) { if(isLegal(temp,rows,cols)) { temp[rows][cols]=‘Q‘; procedure(temp,rows+1); temp[rows][cols]=‘.‘; } } return ; } vector<vector<string> > solveNQueens(int n) { if(n==1) { vector<string> t1(1,"Q"); vector<vector<string>> res1(1,t1); return res1; } if(n<4) { vector<vector<string>> res2; return res2; } vector<string> temp(n,string(n,‘.‘)); procedure(temp,0); return res; } };
标签:
原文地址:http://www.cnblogs.com/qiaozhoulin/p/4522652.html