又练习了一下backtracking,算是一遍通过。
几个注意的地方:
1. 使用了动态数组之后,注意memset一下清零(三个参数依次是:指针,要设置的值,长度)
2. 注意从第0个Queen开始放,这样便于理解和编程。
3. 注意isValid函数。一般在backtracking中,最好都有这样一个函数,便于程序的结构化。
4. 本次使用的是recursion,其实backtracking显然也可以通过iteration实现,只是麻烦一点。
1068ms 过大集合
class Solution{ bool isValid(int * arr, int len, int QueenToPut, int pos) { bool ret = true; if (QueenToPut == 0) return ret; //always true for the first queen for (int i = 0; i <= QueenToPut - 1; i++) { //the position cannot be equal to any other previous position; also, the two points are (i,arr[i]) and (QueenToPut,pos), they should not in the diagonal position if (abs(i - QueenToPut) == abs(arr[i] - pos) || arr[i] == pos) { ret = false; break; //use as little loop as possible } } return ret; } int QueenHelper(int* arr, int len, int QueenToPut) { int ret = 0; if (QueenToPut == len) //we are done { //print all the possiblities return 1; } for (int i = 0; i < len; i++) { if (isValid(arr, len, QueenToPut, i)) { arr[QueenToPut] = i; //place it ret += QueenHelper(arr, len, QueenToPut + 1); } } return ret; } int totalNQueens(int num) { if (num <= 0) return 0; int arr[num]; memset(arr, 0, num); return QueenHelper(arr, num, 0); } };
这是iteration的backtracking解法,应该也可以通过,不过现在返回的vector并非总个数,而是每个queen的位置。在本机debug了一下可以通过。
iteration的解法大概要70行,而且陷阱比较多。recursion的解法大概要40行,逻辑容易很多,所以还是推荐recursion解法。
iteration解法中,值得一提的是forward这个变量的用法,要好好体会。
class SolutionOK { public: //像这种一重一重的iteration,不如用recursion bool isValid(vector<int> arr, int row, int queenPos, int max) { int i; bool ret = true; if (queenPos > max) //!! this sentence has the highest priority~!!! return false; if (row == 1) return ret; //always true for row 1 for (i = 1; i < row; i++) { if (arr[i] == queenPos || abs(i - row) == abs(arr[i] - queenPos)) { ret = false; break; } } return ret; } public: vector<vector<int> > Queen(int n) { vector<int> result(n + 1); vector<vector<int> > ret; int index = 1; bool forward = true; int nextQueenPos = 1; while (index >= 1) { if (forward) { if (isValid(result, index, nextQueenPos, n)) { if (index == n) { result[index] = nextQueenPos; ret.push_back(result); forward = false; } else { result[index++] = nextQueenPos; nextQueenPos = 1; //next position } } else forward = false; } else { nextQueenPos++; if (nextQueenPos > n) { index--; nextQueenPos = result[index] + 1; //would plus 1 in the next loop } if (isValid(result, index, nextQueenPos, n)) // result[index] = nextQueenPos;//这里面不修改结果 forward = true; } } return ret; } };