[Leetcode][Python]52: N-Queens II

# -*- coding: utf8 -*-‘‘‘__author__ = ‘[email protected]‘

52: N-Queens IIhttps://oj.leetcode.com/problems/n-queens-ii/

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

===Comments by Dabay===不知道和N Queen相比有没有简单很多的方法。我这里的解法思路和N Queen一样的。

一个一个放皇后,知道能放下最后一个皇后,解法+1。放第k个皇后的时候,在第k行中找位置,先看列被占用没有,然后往左上和右上看斜线被占用没有。‘‘‘

class Solution:    # @return an integer    def totalNQueens(self, n):        def check_up(r, c, board):            for row in xrange(r):                if board[row][c] == ‘Q‘:                    return False            else:                return True

        def check_upleft(r, c, board):            row = r - 1            column = c - 1            while row>=0 and column>=0:                if board[row][column] == ‘Q‘:                    return False                row = row - 1                column = column - 1            else:                return True

        def check_upright(r, c, board):            row = r - 1            column = c + 1            while row>=0 and column<len(board):                if board[row][column] == ‘Q‘:                    return False                row = row - 1                column = column + 1            else:                return True

        def DFS(board, queens, res):            if queens == 0:                res[0] = res[0] + 1                return            r = len(board) - queens            for c in xrange(len(board)):                if not check_up(r, c, board) or not check_upleft(r, c, board) or not check_upright(r, c, board):                    continue                else:                    board[r][c] = ‘Q‘                    DFS(board, queens-1, res)                    board[r][c] = ‘.‘

        board = [[‘.‘] * n for _ in xrange(n)]        #print board        queens = n        res = [0]        DFS(board, queens, res)        return res[0]

def main():    sol = Solution()    print sol.totalNQueens(5)

if __name__ == "__main__":    import time    start = time.clock()    main()    print "%s sec" % (time.clock() - start)
时间: 2025-01-01 16:20:31

[Leetcode][Python]52: N-Queens II的相关文章

[Leetcode][Python]40: Combination Sum II

# -*- coding: utf8 -*-'''__author__ = '[email protected]' 40: Combination Sum IIhttps://oj.leetcode.com/problems/combination-sum-ii/ Given a collection of candidate numbers (C) and a target number (T),find all unique combinations in C where the candi

[LeetCode 51&amp;52] N-Queens I &amp; II (N皇后问题)

题目链接:n-queens import java.util.ArrayList; import java.util.Arrays; import java.util.List; /** * 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 dist

leetcode 【 Pascal&#39;s Triangle II 】python 实现

题目: Given an index k, return the kth row of the Pascal's triangle. For example, given k = 3,Return [1,3,3,1]. Note:Could you optimize your algorithm to use only O(k) extra space? 代码:oj测试通过 Runtime: 48 ms 1 class Solution: 2 # @return a list of intege

[leetcode]Unique Binary Search Trees II @ Python

原题地址:https://oj.leetcode.com/problems/unique-binary-search-trees-ii/ 题意:接上一题,这题要求返回的是所有符合条件的二叉查找树,而上一题要求的是符合条件的二叉查找树的棵数,我们上一题提过,求个数一般思路是动态规划,而枚举的话,我们就考虑dfs了.dfs(start, end)函数返回以start,start+1,...,end为根的二叉查找树. 代码: # Definition for a binary tree node #

Pascal&#39;s triangle II Leetcode Python

Given an index k, return the kth row of the Pascal's triangle. For example, given k = 3, Return [1,3,3,1]. Note: Could you optimize your algorithm to use only O(k) extra space? 这题和前面一题的区别在于不用返回所有解,只需要返回index对应行就行.做法和前面的一样定义一个currow 和prerow class Solu

【leetcode】Pascal&#39;s Triangle II (python)

其实每一行的结果是二项式展开的系数,但是考虑到当给定的参数过大的时候,在求组合的过程中会出现溢出(中间过程要用到乘法),但是这样的算法的时间复杂度是O(N),所以在参数不太大的时候,还是不错的. 这里用迭代的方法来求,当然复杂度就高了,是O(N^2),这里主要说下迭代时候的技巧,即在一个列表(数组)里进行迭代,实现如此的操作,要求在求下一行的时候,要从后往前进行,若是从前向后,就把后面要用的变量给改掉了,产生"脏"数据.从后向前不会(为何?),因为下一行比上一行多一个.(自己写写例子看

[leetcode] 52. N皇后 II

52. N皇后 II 跟上个题一模一样,现在只需输出个数即可 class Solution { public int totalNQueens(int n) { boolean[] row = new boolean[n]; boolean[] h = new boolean[2 * n]; boolean[] r = new boolean[2 * n]; List<List<String>> ans = new ArrayList<>(); dfs(n, row,

LeetCode Python 位操作 1

Python 位操作: 按位与 &, 按位或 | 体会不到 按位异或 ^ num ^ num = 0 左移 << num << 1 == num * 2**1 右移 >> num >> 2 == num / 2**2 取反 ~ ~num == -(num + 1) 1. Single Number Given an array of integers, every element appears twice except for one. Find

[LeetCode] 119. Pascal&#39;s Triangle II 杨辉三角 II

Given an index k, return the kth row of the Pascal's triangle. For example, given k = 3,Return [1,3,3,1]. Note:Could you optimize your algorithm to use only O(k) extra space? 118. Pascal's Triangle 的拓展,给一个索引k,返回杨辉三角的第k行. 解法:题目要求优化到 O(k) 的空间复杂,那么就不能把每