回溯算法本質是DFS的一種,先選擇一條路一直走到底 發現不符合要求了再返回 在尋路的過程中, 如果可以提前發現不符合要求 ,則提前終止 即爲剪枝
78.子集問題
給定一組不含重複元素的整數數組 nums,返回該數組所有可能的子集(冪集)。
說明:解集不能包含重複的子集。
示例:
輸入: nums = [1,2,3]
輸出:
[
[3],
[1],
[2],
[1,2,3],
[1,3],
[2,3],
[1,2],
[]
]
第一種形式:依次對於每個元素 我們都可以選取或者不選取,但是都要將index加1 而探路的終止條件就是index==len(nums)。在這種思路下 空集【】即爲三個元素都不選取 但是他的index爲3 所有是一個解
class Solution:
def subsets(self, nums):
"""
:type nums: List[int]
:rtype: List[List[int]]
"""
def DFS(nums,s,index):
#終止條件
if len(nums) == index:
res.append(s)
return
DFS(nums,s+[nums[index]],index+1) #選取當前元素
DFS(nums,s,index+1)#不選取當前元素
res = []
s = []
DFS(nums,s,0)
return res
第二種形式,可以用循環體代替我們選與不選的操作 每次進入新的一層循環 i+=1 所以最多進入三層
每次進入一個新層相當於選擇當前元素 而進入下一個for循環相當於不選擇當前元素
不同點是此方法是每選擇一個元素 就生成一次子集 而第一種是當選擇次數到了3後在加入子集
因爲選過此元素後會進入下一個for循環 所有不會有重複選擇
class Solution:
def subsets(self, nums):
if not nums:
return []
res = []
n = len(nums)
def helper(idx, temp_list):
res.append(temp_list)
for i in range(idx, n):
helper(i + 1, temp_list + [nums[i]])
helper(0, [])
return res
39 組合總和
給定一個數組 candidates 和一個目標數 target ,找出 candidates 中所有可以使數字和爲 target 的組合。
candidates 中的每個數字在每個組合中只能使用一次。
說明:
所有數字(包括目標數)都是正整數。
解集不能包含重複的組合。
示例 1:
輸入: candidates = [10,1,2,7,6,1,5], target = 8,
所求解集爲:
[
[1, 7],
[1, 2, 5],
[2, 6],
[1, 1, 6]
]
第一種方式,同樣對於每個元素 我們都可以選取或者不選取,而終止條件變爲此時的sum==target所以每次循環時要傳入sum變量 由於可以重複選取 所有當選擇此元素後 新的層還可以選擇此元素
class Solution:
def combinationSum(self, candidates: List[int], target: int) -> List[List[int]]:
candidates.sort()
n = len(candidates)
res = []
def helper(i, tmp_sum, tmp):
if tmp_sum > target or i == n:
return
if tmp_sum == target:
res.append(tmp)
return
helper(i, tmp_sum + candidates[i],tmp + [candidates[i]])#選擇當前元素
helper(i+1, tmp_sum ,tmp)#不選擇當前元素
helper(0, 0, [])
return res
第二種方式 思路一樣 只是用循環體來表示
class Solution:
def combinationSum(self, candidates: List[int], target: int) -> List[List[int]]:
candidates.sort()
n = len(candidates)
res = []
def backtrack(i, tmp_sum, tmp):
if tmp_sum > target or i == n:
return
if tmp_sum == target:
print(tmp)
res.append(tmp)
return
for j in range(i, n):
print(j,tmp_sum,tmp)
if tmp_sum + candidates[j] > target:
break
backtrack(j,tmp_sum + candidates[j],tmp+[candidates[j]])
backtrack(0, 0, [])
return res
40. 組合總和 II
較上一題不同的是有重複的數字且每個數字只能選取一次
給定一個數組 candidates 和一個目標數 target ,找出 candidates 中所有可以使數字和爲 target 的組合。
candidates 中的每個數字在每個組合中只能使用一次。
說明:
所有數字(包括目標數)都是正整數。
解集不能包含重複的組合。
示例 1:
輸入: candidates = [10,1,2,7,6,1,5], target = 8,
所求解集爲:
[
[1, 7],
[1, 2, 5],
[2, 6],
[1, 1, 6]
]
第一種方式,由於有重複的元素 所以要考慮去重 第一種方式考慮在每次添加元素時進行去重
class Solution:
def combinationSum2(self, candidates: List[int], target: int) -> List[List[int]]:
if(not candidates):
return []
n=len(candidates)
candidates.sort()
res=[]
def helper(j,tmp,sum1):
if(j==n or sum1>target):
#print(sum1)
return
if sum1 == target:
if tmp not in res:
res.append(tmp)
#print(tmp)
return
if j+1 ==n and sum1+candidates[j] ==target: #爲了特判【1,1,1】target=3 這種特殊情況
if tmp+[candidates[j]] not in res:
res.append(tmp+[candidates[j]])
if candidates[j] == target: #由於此方法不能再次選取自己 對應末尾的等於targe的元素會判斷不了 所以加一個特判
if [candidates[j]] not in res:
res.append([candidates[j]])
#print(tmp)
return
helper(j+1,tmp+[candidates[j]],sum1+candidates[j])
helper(j+1,tmp,sum1)
helper(0,[],0)
return res
此題推薦用第二種方式 因爲用循環體可以方便的進行去重 首先將數組排序
如果發現排序後兩個相鄰元素相同 直接continue 不對當前元素進行操作
if j > i and candidates[j] == candidates[j-1]:
continue
完整代碼如下
class Solution:
def combinationSum2(self, candidates: List[int], target: int) -> List[List[int]]:
if not candidates:
return []
candidates.sort()
n = len(candidates)
res = []
def backtrack(i, tmp_sum, tmp_list):
if tmp_sum == target:
res.append(tmp_list)
return
for j in range(i, n):
if tmp_sum + candidates[j] > target : break
if j > i and candidates[j] == candidates[j-1]:continue
backtrack(j + 1, tmp_sum + candidates[j], tmp_list + [candidates[j]])
backtrack(0, 0, [])
return res
先介紹這麼多 還有一些回溯問題下次再講