当前位置:网站首页>[backtracking method] backtracking method to solve the problem of Full Permutation
[backtracking method] backtracking method to solve the problem of Full Permutation
2022-06-12 04:44:00 【Empty city ZA】
- subject : Give an array without duplicate numbers nums , Return all possible permutations . You can return the answers in any order .
- Example 1:
Input :nums = [1,2,3]
Output :[[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]]
Topic link :https://leetcode-cn.com/problems/permutations/
class Solution:
def permute(self, nums: List[int]) -> List[List[int]]:
res = []
path = []
n = len(nums)
def backtracking(nums, n):
if len(path) == n:
res.append(path[:])
return
for i in range(n):
# Because there are no duplicate elements , So just judge that the current element is
# No in path Array , no need used Array
if nums[i] not in path:
path.append(nums[i])
backtracking(nums, n)
path.pop()
else:
continue
backtracking(nums, n)
return res
- subject 2: Given a sequence that can contain repeating numbers nums , In any order Returns all non repeating permutations .
- Example 1:
Input :nums = [1,1,2]
Output :[[1,1,2],[1,2,1],[2,1,1]]
Topic link :https://leetcode-cn.com/problems/permutations-ii/
class Solution:
def permuteUnique(self, nums: List[int]) -> List[List[int]]:
def backtracking(nums, used):
if len(path) == len(nums):
res.append(path[:])
return
for i in range(len(nums)):
if used[i]:
continue
if i >= 1 and nums[i] == nums[i-1] and not used [i-1]:
continue
used[i] = 1
path.append(nums[i])
backtracking(nums, used)
path.pop()
used[i] = 0
res = []
path = []
nums.sort()
# used Initialization is zero , meaning : stay nums No element in the array is used
# used = [1, 0, 1,] meaning :nums[0],nums[2] Already in use
used = [0 for i in range(len(nums))]
backtracking(nums, used)
return res
- This full permutation problem and the previous subset , The combination problem is the same , You don't need to weigh them together , Remove the weight together .
The whole arrangement is also , Because it is a full permutation, the traversal of each layer is to traverse the whole nums Array , If nums No repetition of elements in , Then we just need to judge the new nums[i] Is it already in path in , But for those with repeating elements nums, We need a new one used Array to determine whether the number has been used .
Be careful : After these questions, we must pay attention to , When you go up on each floor , Be sure to correct the original nums Array to sort , Put the same elements together .
About python Built in full arrangement , Composite library
product The cartesian product ( There is a sampling arrangement to put back )
Namely nums Elements in can be reusedpermutations array ( Do not put the sampling arrangement back )
nums The element in cannot be reusedcombinations Combine , No repetition ( Don't put the sampling combination back )
nums The element in cannot be reusedcombinations_with_replacement Combine , Repeat ( Sampling combination with return )
nums Elements in can be reused
The professional explanation still depends on the official :https://docs.python.org/3.10/library/itertools.html
""" Each function has two arguments , The first is the iteratable object , The second is to extract from the iteratable objects array or Combine Number of elements of """
import itertools
# lis No repeating elements
lis = ['a', 'b', 'c']
# There is a sort of put back ( Elements can be reused )
for i in itertools.product(lis, repeat=2):
print(i, end=' ')
""" There is a sort of put back ( Elements can be reused ): ('a', 'a') ('a', 'b') ('a', 'c') ('b', 'a') ('b', 'b') ('b', 'c') ('c', 'a') ('c', 'b') ('c', 'c') """
# No put back sort ( Elements cannot be reused )
for i in itertools.permutations(lis, 2):
print(i, end=' ')
""" No put back sort ( Elements cannot be reused ): ('a', 'b') ('a', 'c') ('b', 'a') ('b', 'c') ('c', 'a') ('c', 'b') """
# No put back combination ( Elements cannot be reused )
for i in itertools.combinations(lis, 2):
print(i, end=' ')
""" No put back combination ( Elements cannot be reused ): ('a', 'b') ('a', 'c') ('b', 'c') """
# There are put back combinations ( Elements can be reused )
for i in itertools.combinations_with_replacement(lis, 2):
print(i, end=' ')
""" There are put back combinations ( Elements can be reused ): ('a', 'a') ('a', 'b') ('a', 'c') ('b', 'b') ('b', 'c') ('c', 'c') """
# lis2 There are repeating elements in it
lis2 = ['a', 'a', 'c']
# There is a sort of put back ( Elements can be reused )
for i in itertools.product(lis2, repeat=2):
print(i, end=' ')
""" There is a sort of put back ( Elements can be reused ): ( This a Most of them are for explanation , The output sequence has been adjusted ) ('a', 'a')( first a The subscript is 0 Of a, the second a The subscript is 0 Of a) ('a', 'a')( first a The subscript is 0 Of a, the second a The subscript is 1 Of a) ('a', 'a')( first a The subscript is 1 Of a, the second a The subscript is 0 Of a) ('a', 'a')( first a The subscript is 1 Of a, the second a The subscript is 1 Of a) ('a', 'c') ('a', 'c') ( It's similar to the above ) ('c', 'a') ('c', 'a') ('c', 'c') """
# No put back sort ( Elements cannot be reused )
for i in itertools.permutations(lis2, 2):
print(i, end=' ')
""" No put back sort ( Elements cannot be reused ): ('a', 'a') ('a', 'c') ('a', 'a') ('a', 'c') ('c', 'a') ('c', 'a') """
# No put back combination ( Elements cannot be reused )
for i in itertools.combinations(lis2, 2):
print(i, end=' ')
""" No put back combination ( Elements cannot be reused ): ('a', 'a') ('a', 'c') ('a', 'c') """
# There are put back combinations ( Elements can be reused )
for i in itertools.combinations_with_replacement(lis2, 2):
print(i, end=' ')
""" There are put back combinations ( Elements can be reused ): ('a', 'a') ('a', 'a') ('a', 'c') ('a', 'a') ('a', 'c') ('c', 'c') """
边栏推荐
- Day17 array features array boundary array application traversal array multidimensional array creation and traversal arrays operation array bubble sort
- Detailed explanation of software testing process
- JWT learning and use
- 关于线程池需要注意的几点
- In the era of smart retail, Weimeng reshapes the value of "shopping guide"
- Walking "daily question" and "DP"
- 疫情数据分析平台工作报告【3】网站部署
- 疫情数据分析平台工作报告【6】可视化绘图
- Work report of epidemic data analysis platform [1] data collection
- New year news of osdu open underground data space Forum
猜你喜欢

分布式锁介绍

2022 electrician (elementary) operation certificate examination question bank and online simulation examination

MFC General dialog color dialog

D1 哪吒开发板 上电记录
![Work report on epidemic data analysis platform [7] Alibaba cloud related](/img/e2/acc79256f8f90ca730c39ffb941dab.png)
Work report on epidemic data analysis platform [7] Alibaba cloud related

Gavin teacher's perception of transformer live class - rasa dialogue robot project practice in the field of education agency mode and core component source code analysis under the microservice of educ

Detailed explanation of software testing process

InnoDB data storage structure – MySQL
![Work report of epidemic data analysis platform [6] visual drawing](/img/cc/9eaff451068d0efb174b58719c700e.png)
Work report of epidemic data analysis platform [6] visual drawing

MySQL master-slave construction and Django implementation of read-write separation
随机推荐
L1-065 "nonsense code" (5 points)
EnterpriseTECH STAR Question
图解 Apache SkyWalking UI 的使用
疫情数据分析平台工作报告【6.5】疫情地图
mysqld: Can‘t create directory ‘D: oftinstall\mysql57 (Errcode: 2 - No such file or directory)
Based on Visual Studio code Net Maui cross platform mobile application development
WPF data binding (IV)
分布式锁介绍
D1 哪吒开发板 上电记录
疫情数据分析平台工作报告【1】数据采集
L1-064 AI core code valued at 100 million (20 points)
[wechat applet] the mobile terminal selects and publishes pictures
windows如何安装多个版本mysql,如何同时启动
PostgreSQL age XID maintenance prevents the database from being read-only
According to aiqicha, keep went public in Hong Kong and hit the "first share of online fitness"
JWT學習與使用
Kill session? This cross domain authentication solution is really elegant!
Manually encapsulate a foreacht and map
Install/Remove of the Service Denied!
1007- stair climbing