问题描述:
Follow up for N-Queens problem.
Now, instead outputting board configurations, return the total number of distinct solutions.
分析:该题与上道基本一样,只是有些细节需要改变一下,比如这题要求返还的是count值,而这个值是不能通过传参进去来得到的。所以只能通过返回值来实现。
代码如下:248ms
private int solve(int n,int index,List<Integer> tmpList){
if(n==index){
return 1;
}
int count = 0;
for(int col = 0;col<n;col++){
int row = index;
int rowList;
for(rowList = 0;rowList<tmpList.size();rowList++){
int rowrow = rowList;
int colcol = tmpList.get(rowrow);
//同一列
if(col == colcol)
break;
//同一斜线
if(Math.abs(rowrow-row)==Math.abs(colcol-col))
break;
}
if(rowList==tmpList.size()) {
tmpList.add(col);
int val = solve(n, index + 1, tmpList);
tmpList.remove(tmpList.size()-1);
if(val>0) {
count += val;
}
}
}
return count;
}
public int totalNQueens(int n){
List<Integer> tmpList = new LinkedList<>();
return solve(n, 0, tmpList);
}