LeetCode 52. N-Queens II

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

题目:

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 }

AC Python:

 1 class Solution:
 2     def totalNQueens(self, n: int) -> int:
 3         self.res = 0
 4         self.dfs(n, [0] * n, 0)
 5         return self.res
 6     
 7     def dfs(self, n: int, board: List[int], cur: int) -> None:
 8         if cur == n:
 9             self.res += 1
10             return
11         for i in range(n):
12             board[cur] = i
13             if self.isValid(cur, board):
14                 self.dfs(n, board, cur + 1)
15                 
16     def isValid(self, cur: int, board: List[int]) -> bool:
17         for i in range(0, cur):
18             if board[cur] == board[i] or abs(board[cur] - board[i]) == cur - i:
19                 return False
20         
21         return True
22         

类似N-Queens

posted @ 2015-10-29 12:34  Dylan_Java_NYC  阅读(204)  评论(0编辑  收藏  举报