51. N-Queens II
Follow up for N-Queens problem.
Now, instead outputting board configurations, return the total number of distinct solutions.

---
跟50 -Queue思路一样
问题是那个不能用int total带入,而是int[] 即便是一位数组,
如果只是int作为参数,只是copy the value to the function, total本身没有变,
如果是int[], 相当吧variable's reference带入, 可以改变参数本身的值,
试过 Integer,也不行,所以用int[1]吧
---
public class Solution { public int totalNQueens(int n) { int[] total = new int[1]; int[] cols = new int[n]; placeQ(n, 0, cols, total); return total[0]; } private void placeQ(int n, int r, int[] cols, int[] total){ if(r == n){ //Found one! total[0]++; }else{ for(int c=0; c < n; c++){ if(checkValid(cols,r,c)){// if Valid cols[r] = c; // place a Q placeQ(n, r+1, cols, total);// go to next row } } } } private boolean checkValid(int[] cols, int r1, int c1){ for(int r2=0; r2<r1; r2++){ int c2 = cols[r2]; //check if at some col if(c2 == c1) return false; } return true; } }
浙公网安备 33010602011771号