当前位置:网站首页>Thinking about the arrangement problem in the backtracking problem (leetcode questions 46 and 47)
Thinking about the arrangement problem in the backtracking problem (leetcode questions 46 and 47)
2022-07-03 14:13:00 【Hurri_ cane】
Thinking about the arrangement problem in the backtracking problem ( Cattle from 46 Question and 47 topic ),Python Realization
1. Configuration environment
Usage environment :python3.7
platform :Windows10
IDE:PyCharm
2. The origin of blog
Bloggers are brushing LeetCode I have a little thought about the full arrangement problem , Record here .
3. Problem description
array 、 The key problem in combinatorial problems is de duplication , The common method is to adopt used Array for de duplication , But this may not be the best way , With LeetCode46 For example

4. Common methods
Take the method provided by the code Capriccio as an example
Method 1 : use usage_list Array to record , Every time you enter backtracking (backtracking) If yes, you can judge whether to use the modified element , So as to achieve weight removal .
class Solution:
def __init__(self):
self.path = []
self.paths = []
def permute(self, nums: List[int]) -> List[List[int]]:
usage_list = [False] * len(nums)
self.backtracking(nums, usage_list)
return self.paths
def backtracking(self, nums: List[int], usage_list: List[bool]) -> None:
# Base Case Find the leaf node
if len(self.path) == len(nums):
self.paths.append(self.path[:])
return
# Single layer recursive logic
for i in range(0, len(nums)): # Search from scratch
# If self.path The elements included in , skip
if usage_list[i] == True:
continue
usage_list[i] = True
self.path.append(nums[i])
self.backtracking(nums, usage_list) # Vertical transmission of usage information , duplicate removal
self.path.pop()
usage_list[i] = False
Method 2 : lose usage_list, use self.path Instead of , But the thought of weight removal still lies in judgment num[i] Whether it appears in the record , If so, just continue fall
class Solution:
def __init__(self):
self.path = []
self.paths = []
def permute(self, nums: List[int]) -> List[List[int]]:
self.backtracking(nums)
return self.paths
def backtracking(self, nums: List[int]) -> None:
# Base Case Find the leaf node
if len(self.path) == len(nums):
self.paths.append(self.path[:])
return
# Single layer recursive logic
for i in range(0, len(nums)): # Search from scratch
# If self.path The elements included in , skip
if nums[i] in self.path:
continue
self.path.append(nums[i])
self.backtracking(nums)
self.path.pop()
5. My thinking
Ideas :
Whether to use usage_list still self.path It's all about recording element usage through a container , During recursion , Judge all elements once , For the use of elements continue operation .
Perhaps there is a more direct method of weight removal , Enter through control backtracking Of nums Array , Direct pair nums Array for de duplication , Let in backtracking Of nums It has been removed , In the use of for When traversing between layers , You can directly skip the elements being used , The specific operation is as follows :
# author:Hurricane
# date: 2022/7/2
# E-mail:[email protected]
class Solution:
def permute(self, nums):
self.path = []
self.res = []
self.backtracking(nums, len(nums))
return self.res
def backtracking(self, nums, length):
if len(self.path) == length:
self.res.append(self.path[:])
return
for i in range(len(nums)):
self.path.append(nums[i])
self.backtracking(nums[0:i] + nums[i + 1:], length)
self.path.pop()
The core code is
self.backtracking(nums[0:i] + nums[i + 1:], length)
This line of code controls the entry backtracking The elements of , Enter directly from backtracking The source of the finished heavy ,
6. Other similar topics
about LeetCode47 Questions can also be carried out with the same idea 
Here is also the way bloggers think
# author:Hurricane
# date: 2022/7/2
# E-mail:[email protected]
class Solution:
def permuteUnique(self, nums):
self.path = []
self.res = []
nums.sort()
self.backtracking(nums, len(nums))
return self.res
def backtracking(self, nums, length):
if len(self.path) == length:
self.res.append(self.path[:])
return
for i in range(len(nums)):
if i > 0 and nums[i] == nums[i - 1]:
continue
self.path.append(nums[i])
self.backtracking(nums[0:i] + nums[i + 1:], length)
self.path.pop()

7. reference
8. Conclusion
If this article is helpful to you 、 Collect and take away with one click , Your support is my greatest motivation !(づ。◕ᴗᴗ◕。)づ
边栏推荐
- Uio-66-cooh loaded bendamostine | hydroxyapatite (HA) coated MIL-53 (FE) nanoparticles | baicalin loaded manganese based metal organic skeleton material
- Exercise 6-6 use a function to output an integer in reverse order
- Redis: commandes d'action pour les données de type chaîne
- Qt学习21 Qt 中的标准对话框(下)
- Example analysis of QT learning 18 login dialog box
- “又土又穷”的草根高校,凭什么被称为“东北小清华”?
- Leetcode(4)——尋找兩個正序數組的中比特數
- 7-9 find a small ball with a balance
- 【吉林大学】考研初试复试资料分享
- Programmable logic device software testing
猜你喜欢

Dlopen() implements dynamic loading of third-party libraries

concat和concat_ws()区别及group_concat()和repeat()函数的使用

JVM object lifecycle

金属有机骨架MOFs装载非甾体类抗炎药物|ZIF-8包裹普鲁士蓝负载槲皮素(制备方法)
[email protected] Nanoparticles) | nano metal organic framework carry"/>Metal organic framework material zif-8 containing curcumin( [email protected] Nanoparticles) | nano metal organic framework carry

Why are grass-roots colleges and universities with "soil and poverty" called "Northeast small Tsinghua"?

可编程逻辑器件软件测试

Cross linked cyclodextrin metal organic framework loaded methotrexate slow-release particles | metal organic porous material uio-66 loaded with flavonoid glycosides | Qiyue

3D vision - 2 Introduction to pose estimation - openpose includes installation, compilation and use (single frame, real-time video)

Use vscode to view hex or UTF-8 codes
随机推荐
[ACNOI2022]猜数
金属有机骨架(MOFs)抗肿瘤药载体|PCN-223装载甲硝唑|UiO-66包载盐酸环丙沙星([email protected])
[clean up the extraordinary image of Disk C]
JS continues to explore...
Toast UI editor (editor allows you to edit your markup document using text or WYSIWYG, with syntax highlighting, scrolling synchronization, real-time preview and chart functions.)
QT learning 25 layout manager (4)
js . Find the first palindrome string in the array
Rasp implementation of PHP
RocksDB LRUCache
Redis:字符串类型数据的操作命令
6-9 statistics of single digits (15 points)
PCB中常用快捷键
Dlopen() implements dynamic loading of third-party libraries
Use vscode to view hex or UTF-8 codes
Vite project commissioning
How to bold text in AI
Exercise 6-2 using functions to sum special A-string sequences
UiO-66-COOH装载苯达莫司汀|羟基磷灰石( HA) 包裹MIL-53(Fe)纳米粒子|装载黄芩苷锰基金属有机骨架材料
Generate directories from web content
Exercise 10-6 recursively find Fabonacci sequence