[leetcode]N-Queens @ Python

原题地址:https://oj.leetcode.com/problems/n-queens/

题意:经典的N皇后问题。

解题思路:这类型问题统称为递归回溯问题,也可以叫做对决策树的深度优先搜索(dfs)。N皇后问题有个技巧的关键在于棋盘的表示方法,这里使用一个数组就可以表达了。比如board=[1, 3, 0, 2],这是4皇后问题的一个解,意思是:在第0行,皇后放在第1列;在第1行,皇后放在第3列;在第2行,皇后放在第0列;在第3行,皇后放在第2列。这道题提供一个递归解法,下道题使用非递归。

check函数用来检查在第k行,皇后是否可以放置在第j列。

Queen逐行放入棋盘, 每放入一个新的queen, 只需要检查她跟之前的queen是否列冲突和对角线冲突就可以了。如果两个queen的坐标为(i1, j1)和(i2, j2), 当abs(i1 - i2) = abs(j1 - j2)时就对角线冲突。

Since we simplify the solution into 1D, this means:

if:

abs(i - depth) == abs(board[i] - j):

Then:

对角线冲突

This corresponds to two points in the orginal 2D board:

(i, board[i]) and (depth, j)

Code:

class Solution:
    # @return a list of lists of string
    def solveNQueens(self, n):
        def check(depth, j):
            for i in range(depth):
                # board[i] == j:         means jth column is already occupied in the past since i < depth for sure
                # abs(i - depth) == abs(board[i] - j)
                # means diagnoal collission
                # Because, this corresponds to two points in the orginal 2D board: (i, board[i]) and (depth, j)
                #
                if board[i] == j or abs(i - depth) == abs(board[i] - j):
                    return False
            return True

        def dfs(depth, vals):
            if depth == n: res.append(vals); return
            s = ‘.‘*n
            for j in range(n):
                if check(depth, j):
                    board[depth] = j
                    dfs(depth + 1, vals + [ s[:j] + ‘Q‘ + s[j+1:] ])
        board = [-1] * n
        res =[]
        dfs(0,[])
        return res
时间: 2024-08-26 12:53:26

[leetcode]N-Queens @ Python的相关文章

[LeetCode]题解(python):031-Next Permutation

题目来源 https://leetcode.com/problems/next-permutation/ Implement next permutation, which rearranges numbers into the lexicographically next greater permutation of numbers. If such arrangement is not possible, it must rearrange it as the lowest possible

[leetcode]Combination Sum @ Python

原题地址:https://oj.leetcode.com/problems/combination-sum/ 题意: Given a set of candidate numbers (C) and a target number (T), find all unique combinations in C where the candidate numbers sums to T. The same repeated number may be chosen from C unlimited

[leetcode]Interleaving String @ Python

原题地址:https://oj.leetcode.com/problems/interleaving-string/ 题意: Given s1, s2, s3, find whether s3 is formed by the interleaving of s1 and s2. For example,Given:s1 = "aabcc",s2 = "dbbca", When s3 = "aadbbcbcac", return true.Whe

[leetcode]Valid Number @ Python

原题地址:http://oj.leetcode.com/problems/valid-number/ 题意:判断输入的字符串是否是合法的数. 解题思路:这题只能用确定有穷状态自动机(DFA)来写会比较优雅.本文参考了http://blog.csdn.net/kenden23/article/details/18696083里面的内容,在此致谢! 首先这个题有9种状态: 0初始无输入或者只有space的状态1输入了数字之后的状态2前面无数字,只输入了dot的状态3输入了符号状态4前面有数字和有do

[leetcode]Sort List @ Python

原题地址:http://oj.leetcode.com/problems/sort-list/ 题意:链表的排序.要求:时间复杂度O(nlogn),空间复杂度O(1). 解题思路:由于题目对时间复杂度和空间复杂度要求比较高,所以查看了各种解法,最好的解法就是归并排序,由于链表在归并操作时并不需要像数组的归并操作那样分配一个临时数组空间,所以这样就是常数空间复杂度了,当然这里不考虑递归所产生的系统调用的栈.   这里涉及到一个链表常用的操作,即快慢指针的技巧.设置slow和fast指针,开始它们都

【LeetCode】【Python题解】Pascal&#39;s Triangle

Given numRows, generate the first numRows of Pascal's triangle. For example, given numRows = 5, Return [[1],[1,1],[1,2,1],[1,3,3,1],[1,4,6,4,1]] 要求输入一个整数,返回一个表示杨辉三角的数组.我的方法是计算通项公式,首先是编写阶乘函数,然后计算C00,C10,C11即可 利用Python 的map嵌套可以很简洁地实现,核心代码只有一行! class So

[leetcode]Add Binary @ Python

原题地址:https://oj.leetcode.com/problems/add-binary/ 题意: Given two binary strings, return their sum (also a binary string). For example,a = "11"b = "1"Return "100". 解题思路:提供两种实现方式吧. 代码一: class Solution: # @param a, a string # @pa

[leetcode]Gas Station @ Python

原题地址:https://oj.leetcode.com/problems/gas-station/ 题意: There are N gas stations along a circular route, where the amount of gas at station i is gas[i]. You have a car with an unlimited gas tank and it costs cost[i] of gas to travel from station i to

[leetcode]Palindrome Partitioning @ Python

原题地址:https://oj.leetcode.com/problems/palindrome-partitioning/ 题意: Given a string s, partition s such that every substring of the partition is a palindrome. Return all possible palindrome partitioning of s. For example, given s = "aab",Return [

[leetcode]Subsets II @ Python

原题地址:https://oj.leetcode.com/problems/subsets-ii/ 题意: Given a collection of integers that might contain duplicates, S, return all possible subsets. Note: Elements in a subset must be in non-descending order. The solution set must not contain duplicat