leetcode-explore-Queue&Stack

1.Number of islands

class Solution {
//BFS
public:
    int numIslands(vector>& grid) {
        if(grid.size()==0)
            return 0;
        int numisland=0;
        queue> point;
        vector> visited;
        int row=grid.size();
        int col=grid[0].size();
        for(int i=0;i> dir={{0,1},{1,0},{-1,0},{0,-1}};
        
        for(int i=0;i=row||cury<0||cury>=col) continue;
                        if(grid[curx][cury]=='1'&&visited[curx][cury]==0){
                            visited[curx][cury]=1;
                            point.emplace(curx,cury);
                        }
                    }
                        
                        
                    }
                    
                }
            }
        }
         return numisland;
        
    }
};
class Solution {
//dfs
public:
    int numIslands(vector>& grid) {
        if(grid.size()==0) return 0;
        int row=grid.size();
        int col=grid[0].size();
        int numisland=0;
        
        for(int i=0;i>& grid,int i,int j){
        if(i<0||i>=grid.size()||j<0||j>=grid[0].size()||grid[i][j]=='0') return;
        if(grid[i][j]=='1')
            grid[i][j]='0';
        dfs(grid,i+1,j);
        dfs(grid,i-1,j);
        dfs(grid,i,j+1);
        dfs(grid,i,j-1);
    }
};

2.target sum

class Solution {
//dfs
public:
    int findTargetSumWays(vector& nums, int S) {
        int numway=0;
        dfs(nums,0,0,S,numway);
        return numway;
    }
    void dfs(vector& nums,int sum,int n,int target,int &count){
        if(n==nums.size()) return;

        sum+=nums[n];
        if(sum==target&&n==nums.size()-1) count++;
        dfs(nums,sum,n+1,target,count);
        sum-=2*nums[n];
        if(sum==target&&n==nums.size()-1) count++;
        dfs(nums,sum,n+1,target,count);
    
    }
};

 

你可能感兴趣的:(leetcode)