[LeetCode 52] N-Queens II
| COMMENTS
Question
Follow up for N-Queens problem.
Now, instead outputting board configurations, return the total number of distinct solutions.
Stats
Frequency | 3 |
Difficulty | 4 |
Adjusted Difficulty | 2 |
Time to use | ——– |
Ratings/Color = 1(white) 2(lime) 3(yellow) 4/5(red)
Solution
I posted 2 solution by me. Second code is same as this guy’s code.
My code
Using global variable (similar to [LeetCode 51] N-Queens)
1 public class Solution { 2 int res = 0; // res should be global, cause java func cannot return int value back. 3 public int totalNQueens(int n) { 4 //int res = 0; 5 //int[] col4row = new int[n]; 6 helper(n, 0, new int[n]); 7 return res; 8 } 9 10 private void helper(int n, int row, int[] col4row) { 11 if(row == n) { // all positions are ok 12 ++res; 13 return; // do not forget to quit from this recursion here. 14 } 15 for(int i = 0; i < n; i++) { 16 col4row[row] = i; // put every col to this row to test the correctness. 17 if(check(row, col4row)) { 18 helper(n, row+1, col4row); 19 } 20 } 21 } 22 23 private boolean check(int row, int[] col4row) { 24 for(int i = 0; i < row; i++) { 25 if(col4row[i] == col4row[row] || 26 Math.abs(col4row[i]-col4row[row]) == row-i) 27 return false; 28 } 29 return true; 30 } 31 }
Without using global variable,
public class Solution { public int totalNQueens(int n) { return solve(0, n, new int[n]); } private int solve(int row, int n, int[] col4row) { if (row == n) return 1; int ans = 0; for (int i = 0; i < n; i++) { boolean conflict = false; for (int j = 0; j < row; j++) // check first, if not ok then go to next col, if ok let col4row[row] = i; if (i == col4row[j] || row - j == Math.abs(i - col4row[j])) conflict = true; if (conflict) continue; col4row[row] = i; ans += solve(row + 1, n, col4row); // this row is finished, go to next row } return ans; } }
时间: 2024-12-24 23:44:23