Brute Force:
1 class Solution { 2 public: 3 bool notExist(vector<int> rec, int level, int current) { 4 for (int i = 0; i < level; i++) { 5 if (rec[i] == current) return false; 6 if (fabs(rec[i] - current) == fabs(level - i)) return false; 7 } 8 return true; 9 } 10 void genQueen(vector<int> rec, vector<string> &result) { 11 for (int i = 0; i < rec.size(); i++) { 12 ostringstream oss; 13 for (int j = 0; j < rec.size(); j++) { 14 if (rec[i] == j) oss << ‘Q‘; 15 else oss << ‘.‘; 16 } 17 result.push_back(oss.str()); 18 } 19 } 20 void getQueen(vector<vector<string> > &result, vector<int> rec, int n, int level) { 21 if (level == n) { 22 result.push_back(vector<string>()); 23 genQueen(rec, result.back()); 24 return; 25 } 26 for (int i = 0; i < n; i++) { 27 if (notExist(rec, level, i)) { 28 rec[level] = i; 29 getQueen(result, rec, n, level+1); 30 } 31 } 32 } 33 vector<vector<string> > solveNQueens(int n) { 34 vector<vector<string> > result; 35 getQueen(result, vector<int> (n,0), n, 0); 36 return result; 37 } 38 };
时间: 2024-10-11 20:59:33