很惊奇这题一次过了,不过我的code感觉比较冗长,建议看网上答案
1 class Solution { 2 public: 3 void dfs(vector<bool> &visit, vector<int> &rec, vector<vector<string>> &ret, int dep, int n) { 4 if (dep == n) { 5 vector<string> tmp(n, ""); 6 for (int i = 0; i < n; i++) { 7 for (int j = 0; j < n; j++) { 8 if (j == rec[i]) tmp[i] += 'Q'; 9 else tmp[i] += '.'; 10 } 11 } 12 ret.push_back(tmp); 13 } 14 vector<bool> cur(n, false); 15 for (int i = 0; i < dep; i++) { 16 if (rec[i] + dep - i < n && rec[i] + dep - i >= 0) cur[rec[i]+dep-i] = true; 17 if (rec[i] - dep + i < n && rec[i] - dep + i >= 0) cur[rec[i]-dep+i] = true; 18 } 19 for (int i = 0; i < n; i++) { 20 if (!cur[i] && !visit[i]) { 21 visit[i] = true; 22 rec[dep] = i; 23 dfs(visit, rec, ret, dep+1, n); 24 rec[dep] = n; 25 visit[i] = false; 26 } 27 } 28 } 29 vector<vector<string> > solveNQueens(int n) { 30 // Start typing your C/C++ solution below 31 // DO NOT write int main() function 32 vector<vector<string>> ret; 33 vector<bool> visit(n, false); 34 vector<int> rec(n, n); 35 dfs(visit, rec, ret, 0, n); 36 return ret; 37 } 38 };
C#
1 public class Solution { 2 public void dfs(ref List<bool> visit, ref List<int> rec, ref List<string[]> ans, int dep, int n) 3 { 4 if (dep == n) { 5 string[] tmp = new string[n]; 6 for (int i = 0; i < n; i++) { 7 for (int j = 0; j < n; j++) { 8 if (j == rec[i]) tmp[i] += 'Q'; 9 else tmp[i] += '.'; 10 } 11 } 12 ans.Add(tmp); 13 return; 14 } 15 List<bool> cur = new List<bool>(n); 16 for (int i = 0; i < n; i++) cur.Add(false); 17 for (int i = 0; i < dep; i++) { 18 if (rec[i] + dep - i < n && rec[i] + dep - i >= 0) cur[rec[i] + dep - i] = true; 19 if (rec[i] - dep + i < n && rec[i] - dep + i >= 0) cur[rec[i] - dep + i] = true; 20 } 21 for (int i = 0; i < n; i++) { 22 if (cur[i] == false && visit[i] == false) { 23 visit[i] = true; 24 rec[dep] = i; 25 dfs(ref visit, ref rec, ref ans, dep+1, n); 26 rec[dep] = n; 27 visit[i] = false; 28 } 29 } 30 } 31 public List<string[]> SolveNQueens(int n) { 32 List<string[]> ans = new List<string[]>(); 33 List<bool> visit = new List<bool>(); 34 List<int> rec = new List<int>(); 35 for (int i = 0; i < n; i++) { 36 visit.Add(false); 37 rec.Add(n); 38 } 39 dfs(ref visit, ref rec, ref ans, 0, n); 40 return ans; 41 } 42 }