当前位置:网站首页>Recursion / backtracking (middle)
Recursion / backtracking (middle)
2022-07-29 00:21:00 【std i hurt o love】
One 、 Number of Islands
Solution 1 :dfs( recommend )
Depth-first search (dfs): Depth first search is generally used to traverse trees or graphs , Others with branches ( Such as two-dimensional matrix ) Also applicable . Its principle is to start from the initial point , Go all the way down the same branch , Until the end of the branch , Then go back to the upper level and continue to follow a branch to the end , So back and forth , Until all nodes are accessed .
- First judge the empty matrix
- Traverse the elements of every position of the matrix from top to bottom and from left to right , If the value is 1, Count the number of islands
- take 1 Change it to 0, Indicates that it has been counted , use dfs Judge whether the four directions are 1, Enter the four branches respectively and continue to modify
class Solution {
public:
void dfs(vector<vector<char>>&v,int i,int j)
{
int n=v.size(),m=v[0].size();
v[i][j]='0';
// Recursion in four directions
if(i-1>=0&&v[i-1][j]=='1')
dfs(v,i-1,j);
if(i+1<n&&v[i+1][j]=='1')
dfs(v,i+1,j);
if(j-1>=0&&v[i][j-1]=='1')
dfs(v,i,j-1);
if(j+1<m&&v[i][j+1]=='1')
dfs(v,i,j+1);
}
int solve(vector<vector<char> >& grid) {
// write code here
int n=grid.size();
if(!n)
return 0;
int m=grid[0].size(),count=0;
for(int i=0;i<n;i++)
{
for(int j=0;j<m;j++)
{
if(grid[i][j]=='1')
{
count++;
dfs(grid,i,j);
}
}
}
return count;
}
};
Time complexity :O(nm), among m、n Is the length and width of the matrix , You need to traverse the entire matrix , Every time dfs The search needs to go through each value of 1 The elements of , But in the worst case, it just turns the whole matrix into 0, Therefore, it is equivalent to the worst ergodic matrix 2 Time
Spatial complexity :O(nm), At worst, the whole matrix is 1, The recursive stack depth is m*n
Solution 2 :bfs
Breadth first search is different from depth first search , It is to access all other nodes directly connected to a node once in turn , Go deeper , Enter the node directly connected to other nodes .bfs We often use the first in, first out of the queue , Because starting from a certain node , We will queue the nodes directly connected to it , They enter first , Will pop up first , When they pop up, add the nodes directly connected to them , Thus, you can access by layer .
- The priority judgment matrix is empty
- Traverse the elements of every position of the matrix from top to bottom and from left to right , If the value is 1, Count the number of islands
- Use bfs Will traverse the matrix encountered 1 And adjacent 1 Set as 0, Each time the queue enters the first 1, Traverse the queue , Explore whether there are four directions 1, Have set as 0, And the position coordinates enter the queue , Continue to traverse until the queue is empty
class Solution {
public:
int solve(vector<vector<char> >& grid) {
// write code here
int n=grid.size();
if(!n)
return 0;
int m=grid[0].size(),count=0;
for(int i=0;i<n;i++)
{
for(int j=0;j<m;j++)
{
if(grid[i][j]=='1')
{
count++;
grid[i][j]='0';
queue<pair<int,int>>q;
q.push({
i,j});
while(!q.empty())//bfs
{
auto tmp=q.front();
q.pop();
int row=tmp.first,col=tmp.second;
if(row-1>=0&&grid[row-1][col]=='1')
{
q.push({
row-1,col});
grid[row-1][col]='0';
}
if(row+1<n&&grid[row+1][col]=='1')
{
q.push({
row+1,col});
grid[row+1][col]='0';
}
if(col-1>=0&&grid[row][col-1]=='1')
{
q.push({
row,col-1});
grid[row][col-1]='0';
}
if(col+1<m&&grid[row][col+1]=='1')
{
q.push({
row,col+1});
grid[row][col+1]='0';
}
}
}
}
}
return count;
}
};
Time complexity :O(n*m), among m、n Is the length and width of the matrix , You need to traverse the entire matrix , Every time bfs The search needs to go through each value of 1 The elements of , But in the worst case, it just turns the whole matrix into 0, Therefore, it is equivalent to the worst ergodic matrix 2 Time
Spatial complexity :(min(n,m)),bfs The worst-case queue size is the smaller value of length and width
Two 、 Arrangement of strings
Solution 1 : violence dfs
- Recursive search for prime , For the first h layer , Enumerate the h A place , What subscript element should be filled
- Be careful : Here, because the string may have duplicate elements , So we record the subscript , Because subscripts cannot be repeated ( It is equivalent to a hash function without hash conflict )
- Then we also need to open one bool Array to record which subscripts have not been used , Ensure that the same subscript is used only once
- Recursive boundary conditions h==s.size(), Because the first h The layer representative is enumerating the h A place ( Namely front h-1 Locations have been enumerated ), So the first h=s.size() The layer represents the front s.size()-1 Layers have been enumerated
- Back in time , Remember to restore the original state
Time complexity , Each layer needs to enumerate whether all numbers can be used , Enumeration is required in total n layer
class Solution {
public:
void dfs(int h,string&s,string&cur,set<string>&res,vector<int>&v)
{
if(h==s.size())// Recursive boundary
{
res.insert(cur);
return;
}
for(int i=0;i<s.size();i++)
{
if(!v[i])// If not used
{
v[i]=1;// Mark as used
cur+=s[i];
dfs(h+1,s,cur,res,v);// recursive
cur.pop_back();// to flash back
v[i]=0;
}
}
}
vector<string> Permutation(string str) {
// write code here
if(str.empty())
return {
};
set<string>res;
vector<int>v(str.size(),0);
string cur;
dfs(0,str,cur,res,v);
return vector<string>({
res.begin(),res.end()});
}
};
The time complexity of this method is too high , It takes up a lot of space
Time complexity :O(n^n)
Spatial complexity :O(n)
Solution 2 :dfs Optimize
public:
void dfs(int h,string&s,set<string>&res){
if(h==s.size()-1){
// Recursive boundary
res.insert(s);// Find a sort , And insert
return ;
}
for(int i=h;i<s.size();i++){
// Suppose the original element is mapped to its subscript , Then we are searching for the full order of subscripts
swap(s[i],s[h]);
dfs(h+1,s,res);// Go to the next level of recursion
swap(s[i],s[h]);// to flash back
}
}
vector<string>Permutation(string str) {
if(str.empty())
return {
};
set<string>res;// Because the title says str There may be repeating elements in , So we need to gather to remove the heavy , And play the role of sorting from small to large
dfs(0,str,res);// Start searching for Strings
return vector<string>({
res.begin(),res.end()});//vector Iterator copy initialization , Just need the same type of element , It's not about the container
}
};
Time complexity :O(n^n)
Spatial complexity :O(n)
Solution 3 : recursive + to flash back ( recommend )
- First, sort the strings in dictionary order , Get the first permutation .
- Prepare an empty string to temporarily store the arrangement assembled during recursion . Use extra v An array is used to record where characters are added .
- Each recursion traverses the string from the beginning , Get characters to add : First of all, according to the v Array , Elements that have been added cannot be added again ; meanwhile , If the current element str[i] The previous element on the same layer str[i-1] Same and str[i-1] Has been used , Nor does it need to be included in .
- Before going to the next level of recursion v The current position of the array is marked as used .
- It needs to be modified during backtracking v Array current position marker , At the same time, remove the element just added to the string ,
- When the length of the temporary string reaches the length of the original string, it is an arrangement .
class Solution {
public:
void fun(vector<string>&res,string&str,string&tmp,vector<int>&v)
{
if(tmp.length()==str.length())
{
res.push_back(tmp);
return ;
}
for(int i=0;i<str.length();i++)
{
if(v[i])// Have used
continue;
if(i>0&&str[i-1]==str[i]&&!v[i-1])// repeat
continue;
v[i]=1;// Mark
tmp.push_back(str[i]);
fun(res,str,tmp,v);
v[i]=0;// to flash back
tmp.pop_back();
}
}
vector<string> Permutation(string str) {
// write code here
sort(str.begin(),str.end());
vector<int>v(str.size(),0);
vector<string>res;
string tmp;
fun(res,str,tmp,v);
return res;
}
};
Sorting with library functions does not require set Containers
Time complexity :O(n∗n!)), All cases of full arrangement are n!, Each recursive process is to traverse the string to find elements , Here is O(n)
Spatial complexity :O(n), The maximum depth of recursive stack is string length n, Temporary string tmp The space is also O(n),res It belongs to returning the necessary space *
边栏推荐
- MySql中的like和in走不走索引
- Control fillet stroke materialshapedrawable
- 跳表的原理
- 【小程序项目开发 -- 京东商城】uni-app 商品分类页面(上)
- Attack and defense world web master advanced area web_ php_ include
- 【C】 Reverse string (two recursive ideas)
- Software designer - intermediate, exam summary
- Android studio连接MySQL并完成简单的登录注册功能
- 2022 network security learning route is very detailed, recommended Learning
- mysql中exists的用法详解
猜你喜欢
"Method not allowed", 405 problem analysis and solution
Build SSM project with JSP as view parser
Idea2021.2 installation and configuration (continuous update)
Table custom style row class name in elemenui
递归/回溯刷题(下)
ACM SIGIR 2022 | interpretation of selected papers of meituan technical team
Solution: direct local.Aar file dependencies are not supported when building an aar
动态规划问题(七)
Servlet operation principle_ API details_ Advanced path of request response construction (servlet_2)
IDEA报错Error running ‘Application‘ Command line is too long解决方案
随机推荐
Applet waterfall flow, upload pictures, simple use of maps
CV instance segmentation model sketch (1)
还在写大量 if 来判断?一个规则执行器干掉项目中所有的 if 判断...
研发效能的道法术器
2022网络安全学习路线 非常详细 推荐学习
[MySQL series] MySQL database foundation
“Method Not Allowed“,405问题分析及解决
Leetcode59. Spiral matrix II
Servlet运行原理_API详解_请求响应构造进阶之路(Servlet_2)
Application of Devops in Internet of things solutions
Intelligent trash can (VII) -- Introduction and use of sg90 steering gear (Pico implementation of raspberry pie)
Solution: direct local.Aar file dependencies are not supported when building an aar
CV semantic segmentation model sketch (2)
【微服务~Nacos】Nacos服务提供者和服务消费者
Advanced area of attack and defense world web masters training www robots
Summary of wrong questions of software designers
Build SSM project with JSP as view parser
What does WGet mean
跳表的原理
110道 MySQL面试题及答案 (持续更新)