这道题其实我原来的思想是对的,不过不知道vector的速度要比数组慢很多,还有就是把参数放到private里也会减少运行时间。memset的时间和一个for循环是一样的,所以以后如果能确定一个数组的size并且不会改变数组大小的,就可以不用vector而用数组。多数次过
1 class Solution { 2 private: 3 int ret; 4 bool visit[100]; 5 int rec[100]; 6 public: 7 bool check(int i, int dep) { 8 for (int j = 0; j < dep; j++) { 9 if (abs(j - dep) == abs(i - rec[j])) return false; 10 } 11 return true; 12 } 13 void dfs(int dep, int n) { 14 if (dep == n) { 15 ret++; 16 return; 17 } 18 for (int i = 0; i < n; i++) { 19 if (!visit[i] && check(i, dep)) { 20 visit[i] = true; 21 rec[dep] = i; 22 dfs(dep+1, n); 23 visit[i] = false; 24 } 25 } 26 } 27 int totalNQueens(int n) { 28 // Start typing your C/C++ solution below 29 // DO NOT write int main() function 30 ret = 0; 31 memset(visit, false, sizeof(visit)); 32 dfs(0, n); 33 return ret; 34 } 35 };
C#
1 public class Solution { 2 public int TotalNQueens(int n) { 3 int ans = 0; 4 bool[] visit = new bool[100]; 5 int[] rec = new int[100]; 6 dfs(0, n, ref ans, ref visit, ref rec); 7 return ans; 8 } 9 public void dfs(int dep, int n, ref int ans, ref bool[] visit, ref int[] rec) { 10 if (dep == n) { 11 ans++; 12 return; 13 } 14 for (int i = 0; i < n; i++) { 15 if (!visit[i] && check(i, dep, ref rec)) { 16 visit[i] = true; 17 rec[dep] = i; 18 dfs(dep+1, n, ref ans, ref visit, ref rec); 19 visit[i] = false; 20 } 21 } 22 } 23 public bool check(int i, int dep, ref int[] rec) { 24 for (int j = 0; j < dep; j++) { 25 if (Math.Abs(j - dep) == Math.Abs(i - rec[j])) return false; 26 } 27 return true; 28 } 29 }