回溯的问题合集(Leetcode题解-Python语言)
生活随笔
收集整理的這篇文章主要介紹了
回溯的问题合集(Leetcode题解-Python语言)
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
78. 子集
要找出所有子集,對于數組里的每個元素,都只有選或不選兩種情況,所以從下標 i = 0 開始,包括或不包括 nums[i],然后對下一個位置 i + 1 進行同樣操作。由于 cur 數組是會變的,所以要 copy 或者 cur[:]
77. 組合
對于組合,考慮了數字 i,后面添加的數要大于 i
39. 組合總和
46. 全排列
排列從思路上是逐個添加,但是代碼實現上要用逐個排除的方法。
90. 子集 II
40. 組合總和 II
class Solution:def combinationSum2(self, candidates: List[int], target: int) -> List[List[int]]:candidates.sort()ans = []cur = []def dfs(pos, total):if total == target:ans.append(cur.copy())returnif pos >= len(candidates) or total > target:returnpre = -1for i in range(pos, len(candidates)):if candidates[i] == pre:continuecur.append(candidates[i])dfs(i + 1, total + candidates[i])cur.pop()pre = candidates[i]dfs(0, 0)return ans47. 全排列 II
class Solution:def permuteUnique(self, nums: List[int]) -> List[List[int]]:ans = []cur = []counter = collections.Counter(nums)def dfs():if len(cur) == len(nums):ans.append(cur.copy())returnfor i in counter:if counter[i] > 0:cur.append(i)counter[i] -= 1dfs()cur.pop()counter[i] += 1dfs()return ans總結
以上是生活随笔為你收集整理的回溯的问题合集(Leetcode题解-Python语言)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Counterpoint:中国高端智能手
- 下一篇: DNF最好的光剑武器——剑魂武器第一选择