当前位置:网站首页>递归/回溯刷题(上)
递归/回溯刷题(上)
2022-07-27 19:04:00 【std i hurt o love】
一、没有重复项数字的全排列
解法一:递归+回溯(推荐)
- 例如[1,2,3,4],如果遍历经过元素2后,前半部分1和2的位置就不变了,对3,4进行排序,后半部分就相当于一个全排列,即为子问题
- 当到数组末尾时终止
- 使用递归的同时还要使用回溯,返回开始进行不同分支选择
public:
void fun(vector<vector<int>>&tmp,vector<int>&num,int index)
{
int n=num.size();
if(index==n-1)//分支进入结尾找到一种排列
tmp.push_back(num);
else
{
for(int i=index;i<n;i++)
{
swap(num[i],num[index]);//交换
fun(tmp,num,index+1);//继续往后查找
swap(num[i],num[index]);//回溯
}
}
}
vector<vector<int> > permute(vector<int> &num) {
sort(num.begin(),num.end());//升序排
vector<vector<int>>tmp;
fun(tmp,num,0);//地柜获取
return tmp;
}
};
时间复杂度:O(n∗n!),近似O(n^2),n个元素的数组进行全排列的递归,每次递归都要遍历数组
空间复杂度:O(n),递归栈的最大深度为数组长度n,tmp属于返回必要空间
解法二:库函数
使用next_permutation进行全排列
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()));//库函数
return v;
}
};
时间复杂度:O(n!),n个元素的数组进行全排列
空间复杂度:O(1),返回矩阵v属于必要空间,不属于额外空间
二、有重复项数字的全排列
解法一:递归+回溯(推荐)
- 先对数组按照字典序排序
- 准备一个数组暂存递归过程中组装的排列情况。使用额外的back数组用于记录哪些位置的数字被加入了。
- 每次递归从头遍历数组,获取数字加入:首先根据back数组,已经加入的元素不能再次加入了;同时,如果当前的元素num[i]与同一层的前一个元素num[i-1]相同且num[i-1]已经用,也不需要将其纳入。
- 进入下一层递归前将back数组当前位置标记为使用过。
- 回溯的时候需要修改back数组当前位置标记,同时去掉刚刚加入数组的元素,
- 临时数组长度到达原数组长度就是一种排列情况。
class Solution {
public:
void fun(vector<vector<int>>&res,vector<int>&num,vector<int>&tmp,vector<int>back)
{
if(tmp.size()==num.size())//临时数组满了加入输出
{
res.push_back(tmp);
return;
}
for(int i=0;i<num.size();i++)
{
if(back[i])//如果该元素已被加入,无需再入
continue;
if(i>0&&num[i-1]==num[i]&&!back[i-1])//num[i]和num[i-1]已经用过
continue;
back[i]=1;//标记为使用过
tmp.push_back(num[i]);
fun(res,num,tmp,back);
back[i]=0;//回溯
tmp.pop_back();
}
}
vector<vector<int> > permuteUnique(vector<int> &num) {
sort(num.begin(),num.end());
vector<int>back(num.size(),0),//初始化未被使用过
tmp;
vector<vector<int>>res;
fun(res,num,tmp,back);
return res;
}
};
时间复杂度:O(n∗n!),全排列的全部情况为n!,每次递归过程都是遍历数组查找元素,这里是O(n)
空间复杂度:O(n),递归栈的最大深度为数组长度n,临时数组temp的空间也为O(n),res属于返回必要空间
解法二:库函数
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;
}
};
和第一题一样使用
时间复杂度:O(n!),n个元素的数组进行全排列
空间复杂度:O(1),返回矩阵res属于必要空间,不属于额外空间
三、自己实现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;
}
};
时间复杂度:O(n!),n个元素的数组进行全排列
空间复杂度:O(1),返回矩阵res属于必要空间,不属于额外空间
边栏推荐
- Chinese and English instructions - human alpha fetoprotein (AFP) ELISA quantitative Kit
- 2019Q4内存厂商营收排名:三星下滑5%,仅SK海力士、美光维持增长
- Automatic classification of e-commerce UGC pictures using Baidu PaddlePaddle easydl
- 哈希表的查找与插入及删除
- Implicit intent
- 图解 SQL,这也太形象了吧!
- 疫情之下,手机供应链及线下渠道受阻!销量骤降库存严重!
- UNITY--读取Excel
- OPPO造芯计划正式公布:首款芯片或为OPPO M1
- 腾讯云[HiFlow】| 自动化 -------HiFlow:还在复制粘贴?
猜你喜欢

Explain cache consistency and memory barrier

Chinese and English instructions - human alpha fetoprotein (AFP) ELISA quantitative Kit

JVM-内存模型 面试总结
![Thesis appreciation [emnlp18] uses sequence tagging for component parsing](/img/99/98f3e5795407c764907e957f69df10.png)
Thesis appreciation [emnlp18] uses sequence tagging for component parsing
![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

Mobilevit learning notes

Characteristics of exonuclease in Worthington venom and related literature

CBAM learning notes
![[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

中英文说明书丨人甲胎蛋白(AFP)ELISA定量试剂盒
随机推荐
纳微半导体65W 氮化镓(GaN)方案获小米10 Pro充电器采用
Multi person collaborative development specification
The use experience of the product is up to you in the evaluation and exchange meeting of the flying oar frame experience!
UNITY--读取Excel
Paper appreciation [emnlp18] dynamic oracles for top-down and middle order move in reduction component parsing
Comprehensively design an oppe home page -- the style of the search and oper part of the page
Acwing3715. 最少交换次数(冒泡排序法的模拟思路)
Troubleshooting and resolution of program operation problems: an instance of 'std:: Logic_ error‘what(): basic_ string::_ M_ construct null not valid
Box model and element positioning
建筑云渲染的应用正在扩大,越来越多的行业急需可视化服务
[2022 Niuke multi School Game 2] k-link with bracket sequence I
对L1正则化和L2正则化的理解[通俗易懂]
Zibbix installation and deployment
图解 SQL,这也太形象了吧!
Dobot magician robot arm - Introduction
The new CTO strongly prohibits the use of calendar?
Unit-- read Excel
软件测试面试题:设计系统测试计划需要参考的项目文档?
软件测试面试题:软件测试项目从什么时候开始?为什么?
QModbus库使用,并作为ROS节点发布话题及程序CMakelist编写