leetcode题解日练--2016.7.27

来源:互联网 发布:交叉熵 圣经网络 编辑:程序博客网 时间:2024/05/29 02:32

日练三题,冰冻三尺非一日之寒。

今日题目:

1、路径和II; tag:树|DFS

2、唯一BSTII; tag:树|DP

3、岛的数量。 tag:DFS|BFS|Union Find

今日摘录:

五岁时,妈妈告诉我,人生的关键在于快乐。上学后,人们问我长大了要做什么,我写下“快乐”。他们告诉我,我理解错了题目,我告诉他们,他们理解错了人生。

——约翰·列侬

113. Path Sum II | Difficulty: Medium

Given a binary tree and a sum, find all root-to-leaf paths where each path’s sum equals the given sum.

For example:
Given the below binary tree and sum = 22,
5
/ \
4 8
/ / \
11 13 4
/ \ / \
7 2 5 1
return
[
[5,4,11,2],
[5,8,4,5]
]

tag:树|DFS
相关题目:Path Sum
题意:求一棵二叉树中所有和为sum的根节点到叶节点的路径。

思路:
1、DFS的思路,每次到了节点判断左右节点递归去进行,如果都试过了之后再pop当前节点。

/** * Definition for a binary tree node. * struct TreeNode { *     int val; *     TreeNode *left; *     TreeNode *right; *     TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */class Solution {public:    vector<vector<int>> pathSum(TreeNode* root, int sum) {        vector<vector<int>> res;        vector<int>tmp;        dfs(res,root,tmp,sum);        return res;    }    void dfs(vector<vector<int> >&res,TreeNode*root,vector<int>&tmp,int sum)    {        if(!root)   return;        if(!root->left && !root->right)        {            if(root->val==sum)  {tmp.push_back(root->val);res.push_back(tmp);tmp.pop_back();return;}            else if(root->val>sum)  return;        }        tmp.push_back(root->val);        if(root->left)  dfs(res,root->left,tmp,sum-root->val);        if(root->right)  dfs(res,root->right,tmp,sum-root->val);        tmp.pop_back();        return;    }};

结果:16ms

2、看了discuss的别人解法之后将代码简化一下

/** * Definition for a binary tree node. * struct TreeNode { *     int val; *     TreeNode *left; *     TreeNode *right; *     TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */class Solution {public:    vector<vector<int>> pathSum(TreeNode* root, int sum) {        vector<vector<int>> res;        vector<int>tmp;        dfs(res,root,tmp,sum);        return res;    }    void dfs(vector<vector<int> >&res,TreeNode*root,vector<int>&tmp,int sum)    {        if(!root)   return;        tmp.push_back(root->val);        if(!root->left && !root->right&&sum==root->val)        {            res.push_back(tmp);        }        dfs(res,root->left,tmp,sum-root->val);        dfs(res,root->right,tmp,sum-root->val);        tmp.pop_back();    }};

结果:16ms

95. Unique Binary Search Trees II | Difficulty: Medium

Given an integer n, generate all structurally unique BST’s (binary search trees) that store values 1…n.

For example,
Given n = 3, your program should return all 5 unique BST’s shown below.

1 3 3 2 1
\ / / / \ \
3 2 1 1 3 2
/ / \ \
2 1 2 3

tag:树|DP
相关题目:Unique Binary Search Trees
题意:生成1-n这n个数字能够组成的二叉树

思路:
1、与Unique Binary Search Trees不同,这里不仅仅只需要求几种组合,更需要写出具体组合的树。
以n=3举栗说明:
[1,2,3]我们可以怎么建树?是不是分别以1为根,以2为根,以3为根各建一次就行了,那怎么做呢?
以1为根的时候,很显然1左边的元素就是左树木,这里没有就是空,1右边的元素[2,3]是右树,这里对于[2,3]又可以有两种建树方法
其他情况类似

/** * Definition for a binary tree node. * struct TreeNode { *     int val; *     TreeNode *left; *     TreeNode *right; *     TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */class Solution {public:    vector<TreeNode*> generateTrees(int n) {        if (n==0)   return vector<TreeNode*> ();        return genTrees(1,n);    }    vector<TreeNode*> genTrees(int start,int end)    {        vector<TreeNode*> res;        if(start>end)        {            res.push_back(NULL);            return res;        }        else if(start==end)        {            res.push_back(new TreeNode(start));            return res;        }        vector<TreeNode*>left,right;        for(int i=start;i<=end;i++)        {            left = genTrees(start,i-1);            right = genTrees(i+1,end);            for (auto lnode : left)            {                for(auto rnode : right)                {                    TreeNode* root = new TreeNode(i);                    root->left = lnode;                    root->right = rnode;                    res.push_back(root);                }            }        }        return res;    }};

结果:24ms

200. Number of Islands | Difficulty: Medium

Given a 2d grid map of ‘1’s (land) and ‘0’s (water), count the number of islands. An island is surrounded by water and is formed by connecting adjacent lands horizontally or vertically. You may assume all four edges of the grid are all surrounded by water.

Example 1:

11110
11010
11000
00000
Answer: 1

Example 2:

11000
11000
00100
00011
Answer: 3

tag:DFS|BFS|Union find
题意:找到有几个岛,岛是被0包围的1

思路:
1、这类矩形搜索的题目,首先可以考虑DFS或者BFS,首先考虑DFS。
DFS的思想就是首先找到一个1,然后这个时候将结果+1,然后将所有与这个1相邻(包括直接相邻与间接相邻)的1全部置为0.
具体方法是首先往一个方向走,走不通了回溯,然后再换方向。

class Solution {public:    void dfs(vector<vector<char>>& grid,int i,int j)    {        grid[i][j]='0';        if(i>0&&grid[i-1][j]=='1')  dfs(grid,i-1,j)     ;        if(i<grid.size()-1 && grid[i+1][j]=='1')  dfs(grid,i+1,j);        if(j>0&& grid[i][j-1]=='1') dfs(grid,i,j-1);        if(j<grid[0].size()-1 && grid[i][j+1]=='1')   dfs(grid,i,j+1);    }    int numIslands(vector<vector<char>>& grid) {        if(grid.size()==0||grid[0].size()==0)   return 0;        int res = 0;        for(int i=0;i<grid.size();i++)        {            for(int j=0;j<grid[0].size();j++)            {                if(grid[i][j]=='1')                {                    res++;                    dfs(grid,i,j);                }            }        }        return res;    }};

结果:8ms

2、BFS
思路很类似,只是每次找到1个1,都记录其直接相邻的点,存入队列并弹出当前点,直到队列为空为止。

class Solution {public:    void bfs(vector<vector<char>>& grid,int i,int j)    {       queue <vector<int>> Q;       Q.push({i,j});       grid[i][j] = '0';       while(!Q.empty())       {           i = Q.front()[0];           j = Q.front()[1];           Q.pop();           if(i>0 && grid[i-1][j]=='1')           {               grid[i-1][j]='0';               Q.push({i-1,j});           }           if(i<grid.size()-1 && grid[i+1][j]=='1')           {               grid[i+1][j]='0';               Q.push({i+1,j});           }            if(j>0&& grid[i][j-1]=='1')            {                grid[i][j-1] = '0';                Q.push({i,j-1});            }             if(j<grid[0].size()-1 && grid[i][j+1]=='1')             {                 grid[i][j+1] = '0';                 Q.push({i,j+1});             }       }    }    int numIslands(vector<vector<char>>& grid) {        if(grid.size()==0||grid[0].size()==0)   return 0;        int res = 0;        for(int i=0;i<grid.size();i++)        {            for(int j=0;j<grid[0].size();j++)            {                if(grid[i][j]=='1')                {                    res++;                    bfs(grid,i,j);                }            }        }        return res;    }};

结果:24ms

0 0
原创粉丝点击