最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

基于Python數(shù)據(jù)結(jié)構(gòu)之遞歸與回溯搜索

 更新時(shí)間:2020年02月26日 14:41:21   作者:haiyu94  
今天小編就為大家分享一篇基于Python數(shù)據(jù)結(jié)構(gòu)之遞歸與回溯搜索,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧

目錄

1. 遞歸函數(shù)與回溯深搜的基礎(chǔ)知識(shí)

2. 求子集 (LeetCode 78)

3. 求子集2 (LeetCode 90)

4. 組合數(shù)之和(LeetCode 39,40)

5. 生成括號(hào)(LeetCode 22)

6. N皇后(LeetCode 51,52)

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

1. 遞歸函數(shù)與回溯深搜的基礎(chǔ)知識(shí)

遞歸是指在函數(shù)內(nèi)部調(diào)用自身本身的方法。能采用遞歸描述的算法通常有這樣的特征:為求解規(guī)模為N的問題,設(shè)法將它分解成規(guī)模較小的問題,然后從這些小問題的解方便地構(gòu)造出大問題的解,并且這些規(guī)模較小的問題也能采用同樣的分解和綜合方法,分解成規(guī)模更小的問題,并從這些更小問題的解構(gòu)造出規(guī)模較大問題的解。特別地,當(dāng)規(guī)模N=1時(shí),能直接得解。

回溯法(探索與回溯法)是一種選優(yōu)搜索法,又稱為試探法,按選優(yōu)條件向前搜索,以達(dá)到目標(biāo)。但當(dāng)探索到某一步時(shí),發(fā)現(xiàn)原先選擇并不優(yōu)或達(dá)不到目標(biāo),就退回一步重新選擇,這種走不通就退回再走的技術(shù)為回溯法,而滿足回溯條件的某個(gè)狀態(tài)的點(diǎn)稱為“回溯點(diǎn)”。

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思路

在上一題思路的基礎(chǔ)上,當(dāng)nums[i]=nums[i-1]時(shí),添加子集時(shí)只需在上一步增加的子集基礎(chǔ)上進(jìn)行添加nums[i],而不需要對(duì)所有子集進(jìn)行添加nums[i]。故在遞歸返回結(jié)果時(shí),返回兩個(gè)結(jié)果,一個(gè)是所有子集,還有一個(gè)是該步驟中添加的子集的集合。

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. 組合數(shù)之和(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)對(duì)給定的數(shù)字集合進(jìn)行排序

(2)target=T,從數(shù)組中找一個(gè)數(shù)n,target= T-n,如果target= 0,則尋找成功添加結(jié)果,如果taget比候選數(shù)字中的最小值還小,則尋找失敗,不添加

(3)注意:按從小到大的順序進(jìn)行查找,如果某數(shù)已找到,則在找下一個(gè)時(shí),不包括該數(shù)

LeetCode 40 Combination Sum II

該題與上一題相比,區(qū)別在于,給定的集合列表中數(shù)字可能重復(fù),目標(biāo)集合中的數(shù)字只能使用給定集合中的數(shù)字,并且每個(gè)數(shù)字只能使用一次。注意,由于存在重復(fù)的數(shù)字,故需要保證結(jié)果中的路徑集合沒有重復(fù)。所以當(dāng)出現(xiàn)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. 生成括號(hào)(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思路

在任意位置,左括號(hào)的個(gè)數(shù)要大于等于右括號(hào)的個(gè)數(shù),如果左括號(hào)的個(gè)數(shù)有剩余,則+'(‘,遞歸,如果右括號(hào)有剩余,且小于左括號(hào)的的個(gè)數(shù),則 +‘)‘,最后左右括號(hào)都不剩則排列結(jié)束。

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個(gè)皇后,n個(gè)皇后不能發(fā)生攻擊,即行/列/斜沒有其他皇后,要求給出所有解決方案。每次在棋盤上的當(dāng)前位置放置一個(gè)皇后,當(dāng)不與前面行的皇后發(fā)生沖突時(shí),則可以遞歸處理下面行的皇后。因?yàn)橛衝行n列,n個(gè)皇后,故每行可以放一個(gè)皇后,每一列也只能放置一個(gè)皇后。通過檢查第k個(gè)皇后能否被放置在第j列進(jìn)行判斷(不與其他皇后在同行,同列,同斜行)。使用一個(gè)長度為n的列表記錄第k行皇后放置的列位置。

LeetCode 52 N-Queens II

和上一題思路一樣,返回結(jié)果的長度即可

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思路

根據(jù)火柴棒的總長度,求正方形的變長,若變長不為整數(shù),則直接判斷為False。

先將nums按從大到小的順序排序,used為和nums等長的列表,用于記錄第i位的元素是否被用過。

使用遞歸判斷從第i位元素起始,能否找到這樣的組合滿足其長度之和等于正方形的邊長。

(1)若滿足初始條件,則返回結(jié)果(True or False)

(2)若不滿足條件,則進(jìn)行遞歸,在剩下的元素中進(jìn)行選擇,看有沒有滿足情況的,如果沒有滿足情況的,used對(duì)應(yīng)位置改為False,結(jié)果返回False

(3)對(duì)nums中的每個(gè)元素進(jìn)行遍歷,看能否滿足nums中的每個(gè)火柴棒都能找到對(duì)應(yīng)邊的組合,其長度和等于正方形邊長。

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數(shù)據(jù)結(jié)構(gòu)之遞歸與回溯搜索就是小編分享給大家的全部內(nèi)容了,希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。

相關(guān)文章

  • python模塊詳解之pywin32使用文檔(python操作windowsAPI)

    python模塊詳解之pywin32使用文檔(python操作windowsAPI)

    pywin32是一個(gè)第三方模塊庫,主要的作用是方便python開發(fā)者快速調(diào)用windows API的一個(gè)模塊庫,這篇文章主要給大家介紹了關(guān)于python模塊詳解之pywin32使用文檔的相關(guān)資料,文中將python操作windowsAPI介紹的非常詳細(xì),需要的朋友可以參考下
    2024-01-01
  • Python?四舍五入到最接近的十位(最新推薦)

    Python?四舍五入到最接近的十位(最新推薦)

    Python具有三個(gè)內(nèi)置函數(shù)round()、floor()和ceil(),可用于對(duì)數(shù)字進(jìn)行舍入,本篇文章將討論使用Python的ceil()函數(shù)將數(shù)字四舍五入到最接近的十,感興趣的朋友跟隨小編一起看看吧
    2022-04-04
  • Python 異常的捕獲、異常的傳遞與主動(dòng)拋出異常操作示例

    Python 異常的捕獲、異常的傳遞與主動(dòng)拋出異常操作示例

    這篇文章主要介紹了Python 異常的捕獲、異常的傳遞與主動(dòng)拋出異常操作,結(jié)合實(shí)例形式詳細(xì)分析了Python針對(duì)異常捕獲、傳遞、處理等常見操作技巧,需要的朋友可以參考下
    2019-09-09
  • Python urlopen()參數(shù)代碼示例解析

    Python urlopen()參數(shù)代碼示例解析

    這篇文章主要介紹了Python urlopen()參數(shù)代碼示例解析,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下
    2020-12-12
  • python url 參數(shù)修改方法

    python url 參數(shù)修改方法

    今天小編就為大家分享一篇python url 參數(shù)修改方法,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧
    2018-12-12
  • Anaconda出現(xiàn)CondaHTTPError: HTTP 000 CONNECTION FAILED for url的解決過程

    Anaconda出現(xiàn)CondaHTTPError: HTTP 000 CONNECTION FAILED for url

    使用anaconda創(chuàng)建一個(gè)新的環(huán)境,執(zhí)行“conda create -n scrapyEnv python=3.6”,結(jié)果出現(xiàn)了CondaHTTPError,下面我們就一起來了解一下解決方法吧
    2021-05-05
  • Python爬蟲之爬取我愛我家二手房數(shù)據(jù)

    Python爬蟲之爬取我愛我家二手房數(shù)據(jù)

    我愛我家的數(shù)據(jù)相對(duì)來說抓取難度不大,基本無反爬措施. 但若按照規(guī)則構(gòu)造頁面鏈接進(jìn)行抓取,會(huì)出現(xiàn)部分頁面無法獲取到數(shù)據(jù)的情況.在網(wǎng)上看了幾個(gè)博客,基本上都是較為簡單的獲取數(shù)據(jù),未解決這個(gè)問題,在實(shí)際應(yīng)用中會(huì)出錯(cuò),本文有非常詳細(xì)的代碼示例,需要的朋友可以參考下
    2021-05-05
  • Python如何將模塊打包并發(fā)布

    Python如何將模塊打包并發(fā)布

    這篇文章主要介紹了Python如何將模塊打包并發(fā)布,幫助大家分享自己的模塊,感興趣的朋友可以了解下
    2020-08-08
  • python自動(dòng)化測試中裝飾器@ddt與@data源碼深入解析

    python自動(dòng)化測試中裝飾器@ddt與@data源碼深入解析

    最近工作中接觸了python自動(dòng)化測試,所以下面這篇文章主要給大家介紹了關(guān)于python自動(dòng)化測試中裝飾器@ddt與@data源碼解析的相關(guān)資料,文中通過實(shí)例代碼介紹的非常詳細(xì),需要的朋友可以參考下
    2022-12-12
  • python基礎(chǔ)教程之while循環(huán)

    python基礎(chǔ)教程之while循環(huán)

    這篇文章主要給大家介紹了關(guān)于python基礎(chǔ)教程之while循環(huán)的相關(guān)資料,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家學(xué)習(xí)或者使用python具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面來一起學(xué)習(xí)學(xué)習(xí)吧
    2019-08-08

最新評(píng)論

嘉定区| 南宁市| 临夏县| 胶南市| 恭城| 邻水| 长海县| 吉林省| 页游| 新建县| 车险| 芮城县| 安义县| 金华市| 清涧县| 天峨县| 乐平市| 讷河市| 柳河县| 穆棱市| 五家渠市| 城固县| 仁怀市| 新兴县| 固安县| 微山县| 天峻县| 波密县| 沛县| 苏尼特右旗| 墨玉县| 临高县| 夏河县| 陇西县| 铜梁县| 吐鲁番市| 长岛县| 五指山市| 曲沃县| 阿鲁科尔沁旗| 绍兴县|