当前位置:网站首页>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
边栏推荐
- zibbix安装部署
- 2019Q4内存厂商营收排名:三星下滑5%,仅SK海力士、美光维持增长
- MobileVIT学习笔记
- Plato Farm在Elephant Swap上铸造的ePLATO是什么?为何具备高溢价?
- A new technical director asked me to do an IP territorial function~
- STL源码剖析
- 软件测试面试题:系统测试的策略有多少种?
- Dual process theory and triple mental model
- The maximum recommended number of rows for MySQL is 2000W. Is it reliable?
- Big guys, the MySQL version is low and does not support CDC, so canal synchronizes binlog to Kafka and data to cli
猜你喜欢

中英文说明书丨 AbFluor 488 细胞凋亡检测试剂盒

The new CTO strongly prohibits the use of calendar?

MySQL back to table, SQL optimization, four isolation levels, three logs binlog, redo log, undo log

University of Tilburg, Federal University of the Netherlands | neural data to text generation based on small datasets: comparing the added value of two semi supervised learning approvals on top of a l

Worthington毒液中核酸外切酶的特征及相关文献
![Paper appreciation [emnlp18] dynamic oracles for top-down and middle order move in reduction component parsing](/img/bf/5244eafd927ae990551a59dfa7e863.png)
Paper appreciation [emnlp18] dynamic oracles for top-down and middle order move in reduction component parsing

Can single mode and multi-mode of industrial switches replace each other?

图解 SQL,这也太形象了吧!

IDEA连接MySQL数据库并执行SQL查询操作

Force buckle 919. Complete binary tree inserter
随机推荐
综合设计一个OPPE主页--页面的精选配件的设计
软件测试面试题:软件验收测试包括正式验收测试、alpha测试、beta测试三种测试?
What are the product performances of industrial Ethernet switches?
递归/回溯刷题(上)
Chinese and English instructions - human alpha fetoprotein (AFP) ELISA quantitative Kit
Unity installs personal free edition
C language - Introduction - grammar - pointer (12)
软件测试面试题:单元测试、集成测试、系统测试的侧重点是什么?
枚举Enum的简单使用
OPPO造芯计划正式公布:首款芯片或为OPPO M1
Worthington蘑菇多酚氧化酶的特性及测定方案
Analysis of STL source code
Pytest failed and rerun
Behavior level description and RTL level description
软件测试面试题:在windows下保存一个文本文件时会弹出保存对话框,如果为文件名建立测试用例,等价类应该怎样划分?
app测试定位方式
ORA-27300,ORA-27301,ORA-27302,ORA-27303,TNS-2518,TNS-12549,TNS-12560,TNS-00519等告警处理
MySQL back to table, SQL optimization, four isolation levels, three logs binlog, redo log, undo log
LInkedList底层源码
In crsctl, the function of displayed home