基于Python数据结构之递归与回溯搜索

目录

1. 递归函数与回溯深搜的基础知识

2. 求子集 (LeetCode 78)

3. 求子集2 (LeetCode 90)

4. 组合数之和(LeetCode 39,40)

5. 生成括号(LeetCode 22)

6. N皇后(LeetCode 51,52)

7. 火柴棍摆正方形(LeetCode 473)

1. 递归函数与回溯深搜的基础知识

递归是指在函数内部调用自身本身的方法。能采用递归描述的算法通常有这样的特征:为求解规模为N的问题,设法将它分解成规模较小的问题,然后从这些小问题的解方便地构造出大问题的解,并且这些规模较小的问题也能采用同样的分解和综合方法,分解成规模更小的问题,并从这些更小问题的解构造出规模较大问题的解。特别地,当规模N=1时,能直接得解。

回溯法(探索与回溯法)是一种选优搜索法,又称为试探法,按选优条件向前搜索,以达到目标。但当探索到某一步时,发现原先选择并不优或达不到目标,就退回一步重新选择,这种走不通就退回再走的技术为回溯法,而满足回溯条件的某个状态的点称为“回溯点”。

2. 求子集 (LeetCode 78 Subsets)

2.1题目

Given a set of distinct integers, nums, return all possible subsets (the power set).
Note: The solution set must not contain duplicate subsets.

For example,
If nums = [1,2,3], a solution is:
[
[3],
[1],
[2],
[1,2,3],
[1,3],
[2,3],
[1,2],
[]
]

2.2思路

初始化,[ ]的子集为[ [ ] ]

nums[ : n]的子集为所有nums[ : n-1]的子集 加上所有nums[ : n-1]的子集+元素nums[n-1]

2.3代码

class Solution(object):
 def subsets(self, nums):
  """
  :type nums: List[int]
  :rtype: List[List[int]]
  """
  size = len(nums)
  return self.solve(nums, size)
 def solve(self, nums, n):
  if n == 0:
   return [[]]
  temp = self.solve(nums[:n-1], n-1)
  ans = temp[:]
  for i in temp:
   ans.append(i + [nums[n-1]])
  return ans

3. 求子集2 (LeetCode 90 Subsets II)

3.1题目

Given a collection of integers that might contain duplicates, nums, return all possible subsets (the power set).
Note: The solution set must not contain duplicate subsets.

For example,
If nums = [1,2,2], a solution is:
[
[2],
[1],
[1,2,2],
[2,2],
[1,2],
[]
]

3.2思路

在上一题思路的基础上,当nums[i]=nums[i-1]时,添加子集时只需在上一步增加的子集基础上进行添加nums[i],而不需要对所有子集进行添加nums[i]。故在递归返回结果时,返回两个结果,一个是所有子集,还有一个是该步骤中添加的子集的集合。

3.3代码

class Solution(object):
 def subsetsWithDup(self, nums):
  """
  :type nums: List[int]
  :rtype: List[List[int]]
  """
  nums.sort()
  size = len(nums)
  return self.solve(nums, size)[0]

 def solve(self, nums, n):
  if n == 0:
   return [[]],[[]]
  if n == 1:
   return [[],[nums[n-1]]],[[nums[n-1]]]
  temp = self.solve(nums[:n-1], n-1)
  ans = temp[0][:]
  l = len(ans)
  if nums[n-1] == nums[n-2]:
   for i in temp[1]:
    ans.append(i + [nums[n-1]])
  else:
   for i in temp[0]:
    ans.append(i + [nums[n-1]])
  return ans,ans[l:]

4. 组合数之和(LeetCode 39,40 )

4.1题目

LeetCode 39 Combination Sum

Given a set of candidate numbers (C) (without duplicates) 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 number of times.
Note:
All numbers (including target) will be positive integers.
The solution set must not contain duplicate combinations.
For example, given candidate set [2, 3, 6, 7] and target 7,
A solution set is:
[
[7],
[2, 2, 3]
]

LeetCode 40 Combination Sum II

Given a collection of candidate numbers (C) and a target number (T), find all unique combinations in C where the candidate numbers sums to T.
Each number in C may only be used once in the combination.
Note:
All numbers (including target) will be positive integers.
The solution set must not contain duplicate combinations.
For example, given candidate set [10, 1, 2, 7, 6, 1, 5] and target 8,
A solution set is:
[
[1, 7],
[1, 2, 5],
[2, 6],
[1, 1, 6]
]

4.2思路

LeetCode 39 Combination Sum

(1)对给定的数字集合进行排序

(2)target=T,从数组中找一个数n,target= T-n,如果target= 0,则寻找成功添加结果,如果taget比候选数字中的最小值还小,则寻找失败,不添加

(3)注意:按从小到大的顺序进行查找,如果某数已找到,则在找下一个时,不包括该数

LeetCode 40 Combination Sum II

该题与上一题相比,区别在于,给定的集合列表中数字可能重复,目标集合中的数字只能使用给定集合中的数字,并且每个数字只能使用一次。注意,由于存在重复的数字,故需要保证结果中的路径集合没有重复。所以当出现candidates[i]==candidates[i-1],跳过。

4.3代码

LeetCode 39 Combination Sum

class Solution(object):
 def combinationSum(self, candidates, target):
  """
  :type candidates: List[int]
  :type target: int
  :rtype: List[List[int]]
  """
  candidates.sort()
  self.ans = []
  self.solve(candidates, target, 0 ,[])
  return self.ans

 def solve(self, candidates, target, start, path):
  if target == 0:
   self.ans.append(path)
   return
  if target < 0:
   return
  size = len(candidates)
  for i in range(start, size):
   if candidates[i] > target:
    return
   self.solve(candidates, target - candidates[i], i, path + [candidates[i]])

LeetCode 40 Combination Sum II

class Solution(object):
 def combinationSum2(self, candidates, target):
  """
  :type candidates: List[int]
  :type target: int
  :rtype: List[List[int]]
  """
  candidates.sort()
  self.ans = []
  self.solve(candidates, target, 0, [])
  return self.ans

 def solve(self, candidates, target, start, path):
  if target == 0:
   self.ans.append(path)
   return
  if target < 0:
   return
  size = len(candidates)
  for i in range(start, size):
   if i != start and candidates[i] == candidates[i-1]:
    continue
   self.solve(candidates, target - candidates[i], i + 1, path + [candidates[i]])

5. 生成括号(LeetCode 22 Generate Parentheses)

5.1题目

Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses.
For example, given n = 3, a solution set is:
[
“((()))”,
“(()())”,
“(())()”,
“()(())”,
“()()()”
]

5.2思路

在任意位置,左括号的个数要大于等于右括号的个数,如果左括号的个数有剩余,则+'(‘,递归,如果右括号有剩余,且小于左括号的的个数,则 +‘)‘,最后左右括号都不剩则排列结束。

5.3代码

class Solution(object):
 def generateParenthesis(self, n):
  """
  :type n: int
  :rtype: List[str]
  """
  self.res = []
  self.generateParenthesisIter('',n, n)
  return self.res

 def generateParenthesisIter(self, mstr, r, l):
  if r == 0 and l ==0:
   self.res.append(mstr)
  if l > 0:
   self.generateParenthesisIter(mstr+'(', r, l-1)
  if r > 0 and r > l:
   self.generateParenthesisIter(mstr+')', r-1, l)

6. N皇后(LeetCode 51 ,52)

6.1题目

LeetCode 51 N-Queens

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.
For example,
There exist two distinct solutions to the 4-queens puzzle:
[
[“.Q..”, // Solution 1
“…Q”,
“Q…”,
“..Q.”],

[“..Q.”, // Solution 2
“Q…”,
“…Q”,
“.Q..”]
]

LeetCode 52 N-Queens II

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

6.2思路

LeetCode 51 N-Queens

n*n的板上放置n个皇后,n个皇后不能发生攻击,即行/列/斜没有其他皇后,要求给出所有解决方案。每次在棋盘上的当前位置放置一个皇后,当不与前面行的皇后发生冲突时,则可以递归处理下面行的皇后。因为有n行n列,n个皇后,故每行可以放一个皇后,每一列也只能放置一个皇后。通过检查第k个皇后能否被放置在第j列进行判断(不与其他皇后在同行,同列,同斜行)。使用一个长度为n的列表记录第k行皇后放置的列位置。

LeetCode 52 N-Queens II

和上一题思路一样,返回结果的长度即可

6.3代码

LeetCode 51 N-Queens

class Solution(object):
 def solveNQueens(self, n):
  """
  :type n: int
  :rtype: List[List[str]]
  """
  self.ans = []
  self.board = [-1 for i in range(n)]
  self.dfs(0, [], n)
  return self.ans
 def isQueen(self, krow, jcolumn):
  for i in range(krow):
   if self.board[i] == jcolumn or abs(krow-i) == abs(self.board[i] - jcolumn):
    return False
  return True

 def dfs(self, krow, rowlist, n):
  if krow == n:
   self.ans.append(rowlist)
  for i in range(n):
   if self.isQueen(krow,i):
    self.board[krow] = i
    self.dfs(krow + 1,rowlist + ['.' * i + 'Q' + '.' * (n-i-1)],n)

LeetCode 52 N-Queens II

class Solution(object):
 def totalNQueens(self, n):
  """
  :type n: int
  :rtype: int
  """
  self.ans = []
  self.board = [-1 for i in range(n)]
  self.dfs(0, [], n)
  return len(self.ans)
 def isQueen(self, krow, jcolumn):
  for i in range(krow):
   if self.board[i] == jcolumn or abs(krow-i) == abs(self.board[i] - jcolumn):
    return False
  return True

 def dfs(self, krow, rowlist, n):
  if krow == n:
   self.ans.append(rowlist)
  for i in range(n):
   if self.isQueen(krow,i):
    self.board[krow] = i
    self.dfs(krow + 1,rowlist + ['.' * i + 'Q' + '.' * (n-i-1)],n)

7. 火柴棍摆正方形(LeetCode 473 Matchsticks to Square)

7.1题目

Remember the story of Little Match Girl? By now, you know exactly what matchsticks the little match girl has, please find out a way you can make one square by using up all those matchsticks. You should not break any stick, but you can link them up, and each matchstick must be used exactly one time.

Your input will be several matchsticks the girl has, represented with their stick length. Your output will either be true or false, to represent whether you could make one square using all the matchsticks the little match girl has.

Example 1:
Input: [1,1,2,2,2]
Output: true

Explanation: You can form a square with length 2, one side of the square came two sticks with length 1.
Example 2:
Input: [3,3,3,3,4]
Output: false

Explanation: You cannot find a way to form a square with all the matchsticks.

7.2思路

根据火柴棒的总长度,求正方形的变长,若变长不为整数,则直接判断为False。

先将nums按从大到小的顺序排序,used为和nums等长的列表,用于记录第i位的元素是否被用过。

使用递归判断从第i位元素起始,能否找到这样的组合满足其长度之和等于正方形的边长。

(1)若满足初始条件,则返回结果(True or False)

(2)若不满足条件,则进行递归,在剩下的元素中进行选择,看有没有满足情况的,如果没有满足情况的,used对应位置改为False,结果返回False

(3)对nums中的每个元素进行遍历,看能否满足nums中的每个火柴棒都能找到对应边的组合,其长度和等于正方形边长。

7.3代码

class Solution(object):
 def makesquare(self, nums):
  """
  :type nums: List[int]
  :rtype: bool
  """
  total = sum(nums)
  if total%4 != 0 or len(nums)<4: return False
  size = total/4
  nums.sort(reverse=True)
  used = [False]*len(nums)
  def dfs(i, expect):
   if i >= len(nums): return expect%size == 0
   if used[i]: return dfs(i+1, expect)
   used[i] = True
   if nums[i] == expect: return True
   if nums[i] < expect:
    expect -= nums[i]
    available = [j for j in range(i+1, len(nums)) if not used[j]]
    for x in available:
     if dfs(x, expect):
      return True
   used[i] = False
   return False
  for i in range(len(nums)):
   if not dfs(i, size): return False
  return True

以上这篇基于Python数据结构之递归与回溯搜索就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持我们。

(0)

相关推荐

  • python 使用递归回溯完美解决八皇后的问题

    八皇后问题描述:在一个8✖️8的棋盘上,任意摆放8个棋子,要求任意两个棋子不能在同一行,同一列,同一斜线上,问有多少种解法. 规则分析: 任意两个棋子不能在同一行比较好办,设置一个队列,队列里的每个元素代表一行,就能达到要求 任意两个棋子不能在同一列也比较好处理,设置的队列里每个元素的数值代表着每行棋子的列号,比如(0,7,3),表示第一行的棋子放在第一列,第二行的棋子放在第8列,第3行的棋子放在第4列(从0开始计算列号) 任意两个棋子不能在同一斜线上,可以把整个棋盘当作是一个XOY平面,原点在

  • 如何通过python实现全排列

    这篇文章主要介绍了如何通过python实现全排列,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下 itertools模块现成的全排列: for i in itertools.permutations('abcd',4): print ''.join(i) 相关全排列算法: def perm(l): if(len(l)<=1): return [l] r=[] for i in range(len(l)): s=l[:i]+l[i+1:] p=pe

  • python 回溯法模板详解

    什么是回溯法 回溯法(探索与回溯法)是一种选优搜索法,又称为试探法,按选优条件向前搜索,以达到目标.但当探索到某一步时,发现原先选择并不优或达不到目标,就退回一步重新选择,这种走不通就退回再走的技术为回溯法,而满足回溯条件的某个状态的点称为"回溯点". 无重复元素全排列问题 给定一个所有元素都不同的list,要求返回list元素的全排列. 设n = len(list),那么这个问题可以考虑为n叉树,对这个树进行dfs,这个问题里的回溯点就是深度(也就是templist的长度)为n时,回

  • python实现全排列代码(回溯、深度优先搜索)

    从n个不同元素中任取m(m≤n)个元素,按照一定的顺序排列起来,叫做从n个不同元素中取出m个元素的一个排列.当m=n时所有的排列情况叫全排列. 公式:全排列数f(n)=n!(定义0!=1) 1 递归实现全排列(回溯思想) 1.1 思想 举个例子,比如你要对a,b,c三个字符进行全排列,那么它的全排列有abc,acb,bac,bca,cba,cab这六种可能就是当指针指向第一个元素a时,它可以是其本身a(即和自己进行交换),还可以和b,c进行交换,故有3种可能,当第一个元素a确定以后,指针移向第二

  • Python字符串的全排列算法实例详解

    本文实例讲述了Python字符串的全排列算法.分享给大家供大家参考,具体如下: 题目描述 输入一个字符串,按字典序打印出该字符串中字符的所有排列.例如输入字符串abc,则打印出由字符a,b,c所能排列出来的所有字符串abc,acb,bac,bca,cab和cba. 输入描述 输入一个字符串,长度不超过9(可能有字符重复),字符只包括大小写字母. 注意有可能重复,因此需要判断 注意list的append方法和list的+方法的区别 append方法在list后面添加元素 +方法在list后面添加l

  • Python循环实现n的全排列功能

    描述: 输入一个大于0的整数n,输出1到n的全排列: 例如: n=3,输出[[3, 2, 1], [2, 3, 1], [2, 1, 3], [3, 1, 2], [1, 3, 2], [1, 2, 3]] n=4,输出[[4, 3, 2, 1], [3, 4, 2, 1], [3, 2, 4, 1], [3, 2, 1, 4], [4, 2, 3, 1], [2, 4, 3, 1], [2, 3, 4, 1], [2, 3, 1, 4], [4, 2, 1, 3], [2, 4, 1, 3],

  • Python实现全排列的打印

    本文为大家分享了Python实现全排列的打印的代码,供大家参考,具体如下 问题:输入一个数字:3,打印它的全排列组合:123 132 213 231 312 321,并进行统计个数. 下面是Python的实现代码: #!/usr/bin/env python # -*- coding: <encoding name> -*- ''' 全排列的demo input : 3 output:123 132 213 231 312 321 ''' total = 0 def permutationCo

  • 基于Python数据结构之递归与回溯搜索

    目录 1. 递归函数与回溯深搜的基础知识 2. 求子集 (LeetCode 78) 3. 求子集2 (LeetCode 90) 4. 组合数之和(LeetCode 39,40) 5. 生成括号(LeetCode 22) 6. N皇后(LeetCode 51,52) 7. 火柴棍摆正方形(LeetCode 473) 1. 递归函数与回溯深搜的基础知识 递归是指在函数内部调用自身本身的方法.能采用递归描述的算法通常有这样的特征:为求解规模为N的问题,设法将它分解成规模较小的问题,然后从这些小问题的解

  • Python数据结构之递归可视化详解

    目录 1.学习目标 2.递归的调用 3.递归可视化 3.1 turtle 库简介 3.1 递归绘图 1.学习目标 递归函数是直接调用自己或通过一系列语句间接调用自己的函数.递归在程序设计有着举足轻重的作用,在很多情况下,借助递归可以优雅的解决问题.虽然使用递归可以快速的解决一些难题,但由于递归的抽象性,使递归难以掌握.为了更好的理解递归函数背后的思想,本节主要通过可视化方式来了解递归函数的执行步骤. 通过本节学习,应掌握以下内容: 提高对递归的理解 利用可视化理解递归函数背后的思想 2.递归的调

  • python数据结构之搜索讲解

    目录 1. 普通搜索 2. 顺序搜索 1.1 无序下的顺序查找 1.2 有序下的顺序查找 2.二分查找 3.散列查找 3.1 几种散列函数 3.2 处理散列表冲突 3.3 散列表的实现(加1重复) 4.参考资料 往期学习: python数据类型: python数据结构:数据类型. python的输入输出: python数据结构之输入输出及控制和异常. python面向对象: python数据结构面向对象. python算法分析: python数据结构之算法分析. python栈.队列和双端队列:

  • 基于Python的一个自动录入表格的小程序

    ## 帮阿雪写的一个小程序 --------------------------------------------------------------------------------------------------- 上大学的时候,总是会由很多表格需要同学们去搞,尤其是刚开学的那个时候,显然是很烦躁, 阿雪刚开学的时候,作为班干部,表示有时候刚录表不是很熟悉经常会弄到很晚,甚至还会弄错, 这就让我很是触动,所以想帮她搞一搞,顺便增强一下我们的友谊/hhhhhh ------------

  • 10张动图学会python循环与递归问题

    图像(包括动图)是传递信息的一种高效方式,往往能增强表象.记忆与思维等方面的反应强度.所谓一图胜千言,说的就是这个道理. 今天为大家整理了十张动图GIFS,有助于认识循环.递归.二分检索等概念的具体运行情况.代码实例以Python语言编写. 一.循环 GIF1:最简单的 while 循环 GIF 2:带 if/else 的循环 二.递归 GIF 3:递归概念的直接演示 GIF 4:递归斐波拉切代码示例 GIF5: 帕斯卡pascals-triangle三角递归动画代码. GIF6:带代码和动画的

  • 基于Python的Houdini插件开发过程详情

    本文以Python开发为例来进行说明,环境说明: (1) Python 3.x(我用的版本是 3.9 版本) (2)IDE开具 PyCharm(我用的版本是 PyCharm Community Edition 2021.3.2) (3)Houdini,我安装的版本是 Houdini 19.0.455 Python相关环境所在的位置(Shell.Source Editor.Panel Editor) Shell 就简单介绍一下.当执行 python 代码时,如果没有打开 Python Shell,

  • Python实现的数据结构与算法之基本搜索详解

    本文实例讲述了Python实现的数据结构与算法之基本搜索.分享给大家供大家参考.具体分析如下: 一.顺序搜索 顺序搜索 是最简单直观的搜索方法:从列表开头到末尾,逐个比较待搜索项与列表中的项,直到找到目标项(搜索成功)或者 超出搜索范围 (搜索失败). 根据列表中的项是否按顺序排列,可以将列表分为 无序列表 和 有序列表.对于 无序列表,超出搜索范围 是指越过列表的末尾:对于 有序列表,超过搜索范围 是指进入列表中大于目标项的区域(发生在目标项小于列表末尾项时)或者指越过列表的末尾(发生在目标项

  • Java数据结构与算法实现递归与回溯

    目录 1.什么是递归? 2.代码案例一——迷宫问题 3.代码案例二——八皇后问题 1.什么是递归? 简单的说: 递归就是方法自己调用自己,每次调用时传入不同的变量.递归有助于编程者解决复杂的问题,同时可以让代码变得简洁. 看个实际应用场景,迷宫问题(回溯), 递归(Recursion) 我列举两个小案例,来帮助大家理解递归,这里在给大家回顾一下递归调用机制 打印问题 阶乘问题 public static void test(int n) { if (n > 2) { test(n - 1); }

  • 基于Python实现通过微信搜索功能查看谁把你删除了

    场景:查找who删了我,直接copy代码保存到一个python文件who.py,在python环境下运行此文件 代码如下,copy保存到who.py文件在python环境直接运行: #!/usr/bin/env python # coding=utf-8 from __future__ import print_function import os try: from urllib import urlencode, quote_plus except ImportError: from url

  • 基于Python实现层次性数据和闭包性质

    目录 绪论 1.序列的表示 表操作 对链表的映射 2.层次性结构 对树的映射 3.序列做为一种约定的界面 绪论 序对可以为我们提供用于构造复合数据的基本“粘接剂”,鉴于Python中tuple中元素不可变的性质,我们通过list来实现序对,如[1, 2].Python的PyListObject对象中实际是存放的是PyObject*指针, 所以可以将PyListObject视为vecter<PyObject*>.这是一种盒子与指针表示方式(list内的元素表示为一个指向对象盒子的指针).对于[1

随机推荐