暑假算法7.18,Day17
DFS
第一题
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
public boolean hasPathSum(TreeNode root, int targetSum) {
if(root == null){
return false;
}
if(root.left == null && root.right == null){
return root.val == targetSum;
}
return hasPathSum(root.left, targetSum - root.val) || hasPathSum(root.right, targetSum - root.val);
}
}
第二题
class Solution {
public:
vector<int> tmp;
vector<vector<int>> ans;
vector<int> used;
void backtrack(int n,int k,int startindex)
{
if(tmp.size()==k)
{//一次的终止条件
ans.push_back(tmp);
return ;
}
for(int i=startindex;i<=n-(k-tmp.size())+1;i++)
{//开始对后面的数进行递归深入
tmp.push_back(i); //把i插入tmp
backtrack(n,k,i+1);//从i之后开始递归
tmp.pop_back();//i排序成功后把i移除换下一个
}
}
vector<vector<int>> combine(int n, int k) {
backtrack(n,k,1);
return ans;
}
};
第三题
class Solution{
public:
vector<vector<int>>A,P,T;
int dir[4][2]={{0,1},{0,-1},{1,0},{-1,0}};
void DFS(vector<vector<int>>&H,vector<vector<int>>&V,int i,int j){
if(V[i][j]){
return ;
}
V[i][j]=1;
if(P[i][j]&&T[i][j]){
A.push_back({i,j});
}
for(int k=0;k<4;k++){
int xx=i+dir[k][0];
int yy=j+dir[k][1];
if(xx<0||xx>=H.size()||yy<0||yy>=H[0].size()||H[i][j]>H[xx][yy]){
continue;
}
DFS(H,V,xx,yy);
}
}
vector<vector<int>> pacificAtlantic(vector<vector<int>>& heights) {
int R=heights.size();
int C=heights[0].size();
P=T=vector<vector<int>>(R,vector<int>(C,0));
for(int i=0;i<R;i++){
DFS(heights,P,i,0);
DFS(heights,T,i,C-1);
}
for(int j=0;j<C;j++){
DFS(heights,P,0,j);
DFS(heights,T,R-1,j);
}
return A;
}
};