LeetCode 52. N-Queens II

原题链接在这里:https://leetcode.com/problems/n-queens-ii/description/

题目:

Follow up for N-Queens problem.

Now, instead outputting board configurations, return the total number of distinct solutions.

题解:

Here it needs to return possible count. We could use an array of length 1 to store accumlated count.

因为Java是pass by value, 需要这类object结构来保留中间结果.

Time Complexity: expontenial.

Space: O(n). 生成的row大小为n. 用了O(n)层stack.

AC Java:

 1 public class Solution {
 2     public int totalNQueens(int n) {
 3         int [] res = new int[1];
 4         dfs(n,0,new int[n], res);
 5         return res[0];
 6     }
 7     //递归写dfs, 每次往row里面加一个数,若是合法就继续dfs
 8     private void dfs(int n, int cur, int [] row, int [] res){
 9         if(cur == n){
10             res[0]++;
11             return;
12         }
13         for(int i = 0; i<n; i++){
14             row[cur] = i;
15             if(isValid(cur, row)){
16                 dfs(n, cur+1, row, res);
17             }
18         }
19     }
20     //检查现在row 还是否合法
21     private boolean isValid(int cur, int [] row){
22         for(int i = 0; i<cur; i++){
23             if(row[cur] == row[i] || Math.abs(row[cur]-row[i]) == cur-i){
24                 return false;
25             }
26         }
27         return true;
28     }
29 }

类似N-Queens

原文地址:https://www.cnblogs.com/Dylan-Java-NYC/p/4920126.html