Leetcode回溯相关题目Python实现

1、46题,全排列

https://leetcode-cn.com/problems/permutations/

class Solution(object):
    def permute(self, nums):
        """
        :type nums: List[int]
        :rtype: List[List[int]]
        """
        n = len(nums)
        results = []
        def backtrack(first = 0):
            if first == n:
                results.append(nums[:])
                return
            for i in range(first, n):
                nums[first], nums[i] = nums[i], nums[first]
                backtrack(first + 1)
                nums[first], nums[i] = nums[i], nums[first]
        backtrack()
        return results

2、47题,全排列二

https://leetcode-cn.com/problems/permutations-ii/

class Solution(object):
    def permuteUnique(self, nums):
        """
        :type nums: List[int]
        :rtype: List[List[int]]
        """
        n = len(nums)
        results = []
        def backtrack(first = 0):
            if first == n:
                results.append(nums[:])
                return
            s = set()
            for i in range(first, n):
                if nums[i] in s:
                    continue
                s.add(nums[i])
                nums[first], nums[i] = nums[i], nums[first]
                backtrack(first + 1)
                nums[first], nums[i] = nums[i], nums[first]
        backtrack()
        return results

3、51题,N皇后

https://leetcode-cn.com/problems/n-queens/

class Solution(object):
    def solveNQueens(self, n):
        """
        :type n: int
        :rtype: List[List[str]]
        """
        results = []
        result = ["." * n] * n
        l = set()
        c = set()
        x = set()
        y = set()

        def backtrack(first=0):
            if first == n:
                results.append(result[:])
                return
            for i in range(n):
                if i in l or first in c or i - first in x or i + first in y:
                    continue
                l.add(i), c.add(first), x.add(i - first), y.add(i + first)
                result[i] = first * "." + "Q" + (n - first - 1) * "."
                backtrack(first + 1)
                l.remove(i), c.remove(first), x.remove(i - first), y.remove(i + first)
                result[i] = n * "."
        backtrack()
        return results

4、52题,N皇后二

https://leetcode-cn.com/problems/n-queens-ii/

class Solution(object):
    def totalNQueens(self, n):
        """
        :type n: int
        :rtype: int
        """
        self.results = 0
        l = set()
        c = set()
        x = set()
        y = set()

        def backtrack(first=0):
            if first == n:
                self.results += 1
                return
            for i in range(n):
                if i in l or first in c or i - first in x or i + first in y:
                    continue
                l.add(i), c.add(first), x.add(i - first), y.add(i + first)
                backtrack(first + 1)
                l.remove(i), c.remove(first), x.remove(i - first), y.remove(i + first)
        backtrack()
        return self.results

原文地址:https://www.cnblogs.com/weswes/p/12002669.html

时间: 2024-08-10 00:06:15

Leetcode回溯相关题目Python实现的相关文章

LeetCode: Palindrome 回文相关题目

LeetCode: Palindrome 回文相关题目汇总 LeetCode: Palindrome Partitioning 解题报告 LeetCode: Palindrome Partitioning II 解题报告 Leetcode:[DP]Longest Palindromic Substring 解题报告 LeetCode: Valid Palindrome 解题报告

【leetcode】Candy(python)

题目要求比其高的邻居要比本身的奖励多,那么最少也要多一个,所有我们可以找到所有的凹点,凹点如下三种情形. 找到所有的凹点后,我们就可以从凹点处开始向左右两个方向依次查找递增序列,其中每个高的都要比相邻的矮的多一个,比如1,2,5,4.我们找到凹点为1 和4,那么从1开始向左没有其他点,我们向右,依次得到2 比1高,2的糖果应该是1的基础上加1,为2, 5比2高,5的糖果是在2的基础上加1,为3.令一个凹点4, 向左,5比4高,5的糖果应该是在4的基础上加 1,为2,这时我们发现冲突了,从凹点1

[leetcode]LRU Cache (python)

LRU:最近最久未使用,为了得到这个最新最久的信息,需要一种策略来进行记录,如果加入类似时间戳式的字段,那么每次删除的时候,就必须通过遍历才能得到时间信息,或者对时间戳进行排序,但是无论哪种,都是需要额外的维护,维护成本都比较高. 广泛使用的策略是底层用双端队列来进行维护,双端使得在插入删除时操作更简单.而单单使用双端队列似乎还是不够,比如在get 时,还是需要顺序查找给定的key参数的,所以为了能在O(1) 时间获得key 需要类hash的结构,在python里,就用字典. 接下来的事情是,我

[leetcode]Trapping Rain Water @ Python

原题地址:https://oj.leetcode.com/problems/trapping-rain-water/ 题意: Given n non-negative integers representing an elevation map where the width of each bar is 1, compute how much water it is able to trap after raining. For example, Given [0,1,0,2,1,0,1,3,

[leetcode]Longest Consecutive Sequence @ Python

原题地址:https://oj.leetcode.com/problems/longest-consecutive-sequence/ 题意: Given an unsorted array of integers, find the length of the longest consecutive elements sequence. For example,Given [100, 4, 200, 1, 3, 2],The longest consecutive elements seque

01背包问题(回溯法)python实现

接上一篇,同样的01背包问题,上一篇采用动态规划的方法,现在用回溯法解决.回溯法采用深度优先策略搜索问题的解,不多说,代码如下: bestV=0 curW=0 curV=0 bestx=None def backtrack(i): global bestV,curW,curV,x,bestx if i>=n: if bestV<curV: bestV=curV bestx=x[:] else: if curW+w[i]<=c: x[i]=True curW+=w[i] curV+=v[i

[leetcode]Insertion Sort List @ Python

原题地址:http://oj.leetcode.com/problems/insertion-sort-list/ 题意:对链表进行插入排序. 解题思路:首先来对插入排序有一个直观的认识,来自维基百科. 代码循环部分图示: 代码: class Solution: # @param head, a ListNode # @return a ListNode def insertionSortList(self, head): if not head: return head dummy = Lis

[leetcode]Minimum Path Sum @ Python

原题地址:https://oj.leetcode.com/problems/minimum-path-sum/ 题意: Given a m x n grid filled with non-negative numbers, find a path from top left to bottom right which minimizes the sum of all numbers along its path. Note: You can only move either down or r

[leetcode]Balanced Binary Tree @ Python

原题地址:http://oj.leetcode.com/problems/balanced-binary-tree/ 题意:判断一颗二叉树是否是平衡二叉树. 解题思路:在这道题里,平衡二叉树的定义是二叉树的任意节点的两颗子树之间的高度差小于等于1.这实际上是AVL树的定义.首先要写一个计算二叉树高度的函数,二叉树的高度定义为:树为空时,高度为0.然后递归求解:树的高度 = max(左子树高度,右子树高度)+1(根节点要算上).高度计算函数实现后,递归求解每个节点的左右子树的高度差,如果有大于1的