[LeetCode] 52. N-QueensII_Hard tag: DFS, backtracking
2019-05-24 10:40 Johnson_强生仔仔 阅读(260) 评论(0) 编辑 收藏 举报The n-queens puzzle is the problem of placing n queens on an n×n chessboard such that no two queens attack each other.
Given an integer n, return all distinct solutions to the n-queens puzzle.
Each solution contains a distinct board configuration of the n-queens' placement, where 'Q'
and '.'
both indicate a queen and an empty space respectively.
Example:
Input: 4 Output: [ [".Q..", // Solution 1 "...Q", "Q...", "..Q."], ["..Q.", // Solution 2 "Q...", "...Q", ".Q.."] ] Explanation: There exist two distinct solutions to the 4-queens puzzle as shown above.
这个题目就是在的基础上将具体方案变成了方案总数,我们只需要返回len(ans)即可。(同时还可以将drawPuzzle这个函数省略掉)
时间复杂度 = 方案总数 * 构造方案所需时间
O( n ! * n)
Code:
class Solution: def nQueens2(self, n): if n < 1: return 0 ans, nums = [], list(range(n)) self.search(ans, [], nums) return len(ans) def search(self, ans, temp, nums): if not nums: ans.append(temp) else: if self.isValid(temp, nums[i]): self.search(ans, temp + [nums[i]], nums[:i] + nums[i + 1:]) def isValid(self, temp, col): row = len(temp) for r, c in enumerate(temp): if r + c == row + col or r - c == row - col: return False return True