当前位置:网站首页>Recursion / backtracking (Part 1)
Recursion / backtracking (Part 1)
2022-07-27 21:37:00 【std i hurt o love】
One 、 A full arrangement of numbers without duplicates
Solution 1 : recursive + to flash back ( recommend )
- for example [1,2,3,4], If you traverse through elements 2 after , First half part 1 and 2 Your position will remain the same , Yes 3,4 Sort , The second half is equivalent to a full arrangement , That is, the sub problem
- When it reaches the end of the array
- Use recursion and backtracking at the same time , Return to start making different branch selections
public:
void fun(vector<vector<int>>&tmp,vector<int>&num,int index)
{
int n=num.size();
if(index==n-1)// Branch into the end to find an arrangement
tmp.push_back(num);
else
{
for(int i=index;i<n;i++)
{
swap(num[i],num[index]);// In exchange for
fun(tmp,num,index+1);// Keep looking back
swap(num[i],num[index]);// to flash back
}
}
}
vector<vector<int> > permute(vector<int> &num) {
sort(num.begin(),num.end());// Ascending row
vector<vector<int>>tmp;
fun(tmp,num,0);// Ground cabinet acquisition
return tmp;
}
};
Time complexity :O(n∗n!), The approximate O(n^2),n The array of elements is recursively arranged in full , Every recursion must traverse the array
Spatial complexity :O(n), The maximum depth of recursive stack is array length n,tmp It belongs to returning the necessary space
Solution 2 : Library function
Use next_permutation Make a full arrangement
class Solution {
public:
vector<vector<int> > permute(vector<int> &num) {
sort(num.begin(),num.end());
vector<vector<int>>v;
do{
v.push_back(num);
}while(next_permutation(num.begin(), num.end()));// Library function
return v;
}
};
Time complexity :O(n!),n An array of elements is arranged in full
Spatial complexity :O(1), Return matrix v It belongs to the necessary space , It doesn't belong to extra space
Two 、 A full arrangement of numbers with duplicates
Solution 1 : recursive + to flash back ( recommend )
- First, sort the array in dictionary order
- Prepare an array to temporarily store the arrangement assembled during recursion . Use extra back An array is used to record where numbers are added .
- Each recursion traverses the array from the beginning , Get digital join : First of all, according to the back Array , Elements that have been added cannot be added again ; meanwhile , If the current element num[i] The previous element on the same layer num[i-1] Same and num[i-1] Has been used , Nor does it need to be included in .
- Before going to the next level of recursion back The current position of the array is marked as used .
- It needs to be modified during backtracking back Array current position marker , At the same time, remove the elements just added to the array ,
- When the length of the temporary array reaches the length of the original array, it is an arrangement .
class Solution {
public:
void fun(vector<vector<int>>&res,vector<int>&num,vector<int>&tmp,vector<int>back)
{
if(tmp.size()==num.size())// When the temporary array is full, add the output
{
res.push_back(tmp);
return;
}
for(int i=0;i<num.size();i++)
{
if(back[i])// If the element has been added , No re-entry required
continue;
if(i>0&&num[i-1]==num[i]&&!back[i-1])//num[i] and num[i-1] It has been used
continue;
back[i]=1;// Mark as used
tmp.push_back(num[i]);
fun(res,num,tmp,back);
back[i]=0;// to flash back
tmp.pop_back();
}
}
vector<vector<int> > permuteUnique(vector<int> &num) {
sort(num.begin(),num.end());
vector<int>back(num.size(),0),// Initialization is not used
tmp;
vector<vector<int>>res;
fun(res,num,tmp,back);
return res;
}
};
Time complexity :O(n∗n!), All cases of full arrangement are n!, Each recursive process is to traverse the array to find elements , Here is O(n)
Spatial complexity :O(n), The maximum depth of recursive stack is array length n, Temporary array temp The space is also O(n),res It belongs to returning the necessary space
Solution 2 : Library function
class Solution {
public:
vector<vector<int> > permuteUnique(vector<int> &num) {
sort(num.begin(),num.end());
vector<vector<int>>res;
do{
res.push_back(num);
}while(next_permutation(num.begin(), num.end()));
return res;
}
};
Use the same as the first question
Time complexity :O(n!),n An array of elements is arranged in full
Spatial complexity :O(1), Return matrix res It belongs to the necessary space , It doesn't belong to extra space
3、 ... and 、 Realize it by yourself next_permutation
class Solution {
public:
bool mynext_Permutation(vector<int> &num) {
int i = num.size() - 2;
while (i >= 0 && num[i] >= num[i + 1]) {
i--;
}
if (i < 0) {
return false;
}
int j = num.size() - 1;
while (j >= 0 && num[i] >= num[j]) {
j--;
}
swap(num[i], num[j]);
reverse(num.begin() + i + 1, num.end());
return true;
}
vector<vector<int> > permuteUnique(vector<int> &num) {
sort(num.begin(),num.end());
vector<vector<int>>res;
do{
res.push_back(num);
}while(mynext_Permutation(num));
return res;
}
};
Time complexity :O(n!),n An array of elements is arranged in full
Spatial complexity :O(1), Return matrix res It belongs to the necessary space , It doesn't belong to extra space
边栏推荐
- Daily news on July 15, 2022: meta announced the launch of make-a-scene: AI image generation can be controlled based on text and sketches
- Some operations about Anaconda (installing software and quickly opening)
- MobileVIT学习笔记
- Behavior level description and RTL level description
- 聊聊 MySQL 事务二阶段提交
- Postgresql源码(65)新快照体系Globalvis工作原理分析
- 腾讯云[HiFlow】| 自动化 -------HiFlow:还在复制粘贴?
- 软件测试面试题:假设有一个文本框要求输入10个字符的邮政编码,对于该文本框应该怎样划分等价类?
- Principle analysis and best practice of guava cache
- Worthington血浆胺氧化酶 (PAO) 说明书
猜你喜欢

Force buckle 919. Complete binary tree inserter

ECCV 2022 | China University of science and Technology & jd.com proposed: data efficient transformer target detector

Characteristics of exonuclease in Worthington venom and related literature

JVM-内存模型 面试总结
![[2022 Niuke multi School Game 2] k-link with bracket sequence I](/img/95/9d6710bfb7b9282b4a06a5f61a1f08.png)
[2022 Niuke multi School Game 2] k-link with bracket sequence I

Search, insert and delete of hash table

为什么要使用MQ消息中间件?这几个问题必须拿下

"Geography language" large model Wenxin Ernie geol and its application

Technical practice behind bloom model: how to refine 176billion parameter model?

ECCV 2022 | 中科大&京东提出:数据高效的Transformer目标检测器
随机推荐
MySQL data recovery process is based on binlog redolog undo
说明书丨Worthington逆转录酶、重组 HIV 检测方案
软件测试面试题:单元测试、集成测试、系统测试的侧重点是什么?
大佬们,mysql版本低,不支持cdc,所以canal同步binlog至kafka,数据同步至cli
Acwing3715. Minimum exchange times (simulation idea of bubble sorting method)
Oppo core making plan officially announced: the first chip or oppo M1
C language - Introduction - grammar - pointer (12)
What is the value of digital factory management system
puzzle(002)内固、外固、哈密顿
Graphic SQL, this is too vivid!
30分钟彻底弄懂 synchronized 锁升级过程
简单手动实现Map
A new technical director asked me to do an IP territorial function~
[2022 Niuke multi School Game 2] k-link with bracket sequence I
自定义recycleView的删除&移动的动画
MobileVIT学习笔记
The new CTO strongly prohibits the use of calendar?
2019q4 memory manufacturers' revenue ranking: Samsung fell 5%, only SK Hynix and micron maintained growth
Unity installs personal free edition
What are the product performances of industrial Ethernet switches?