提交 668811cd 编写于 作者: 每日一练社区's avatar 每日一练社区

add 11 leetcode exercises

上级 cb7085bb
......@@ -35,7 +35,18 @@
## aop
### before
```cpp
#include <bits/stdc++.h>
using namespace std;
struct TreeNode
{
int val;
TreeNode *left;
TreeNode *right;
TreeNode() : val(0), left(nullptr), right(nullptr) {}
TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
};
```
### after
```cpp
......@@ -44,21 +55,112 @@
## 答案
```cpp
class Solution
{
public:
int maxv = -123123632;
int maxPathSum(TreeNode *root)
{
if (root == NULL)
return 0;
calc(root);
return maxv;
}
int calc(TreeNode *root)
{
if (root == NULL)
return 0;
int temp = root->val;
int lmaxsum = calc(root->left);
int rmaxsum = calc(root->right);
if (lmaxsum > 0)
temp += lmaxsum;
if (rmaxsum > 0)
temp += rmaxsum;
return max(root->val, max(root->val + lmaxsum, root->val + rmaxsum));
}
};
```
## 选项
### A
```cpp
class Solution
{
int res = INT_MIN;
public:
int maxPathSum(TreeNode *root)
{
int p = getdfs(root);
return res;
}
int getdfs(TreeNode *node)
{
if (node == NULL)
return 0;
int left = max(getdfs(node->left), 0);
int right = max(getdfs(node->right), 0);
int size = left + right + node->val;
res = res > size ? res : size;
right = right > left ? right : left;
node->val = right + node->val;
return node->val;
}
};
```
### B
```cpp
class Solution
{
public:
int ans = 0;
int OneSideMax(TreeNode *root)
{
if (root == nullptr)
return 0;
int left = max(0, OneSideMax(root->left));
int right = max(0, OneSideMax(root->right));
ans = max(ans, left + right + root->val);
return max(left, right) + root->val;
}
int maxPathSum(TreeNode *root)
{
OneSideMax(root);
return ans;
}
};
```
### C
```cpp
class Solution
{
public:
int dfs(TreeNode *root, int &res)
{
if (root == NULL)
{
return 0;
}
int left = max(dfs(root->left, res), 0);
int right = max(dfs(root->right, res), 0);
res = max(res, root->val + left + right);
return root->val + max(left, right);
}
int maxPathSum(TreeNode *root)
{
int res = INT_MIN;
dfs(root, res);
return res;
}
};
```
#include <vector>
using std::vector;
#include <unordered_map>
using std::unordered_map;
#include <bits/stdc++.h>
using namespace std;
struct UndirectedGraphNode
class Node
{
int label;
vector<UndirectedGraphNode *> neighbors;
UndirectedGraphNode(int x) : label(x){};
public:
int val;
vector<Node *> neighbors;
Node()
{
val = 0;
neighbors = vector<Node *>();
}
Node(int _val)
{
val = _val;
neighbors = vector<Node *>();
}
Node(int _val, vector<Node *> _neighbors)
{
val = _val;
neighbors = _neighbors;
}
};
class Solution
{
unordered_map<UndirectedGraphNode *, UndirectedGraphNode *> map;
void dfs(UndirectedGraphNode *node)
public:
Node *cloneGraph(Node *node)
{
if (map.find(node) != map.end())
return;
map[node] = new UndirectedGraphNode(node->label);
for (UndirectedGraphNode *neighbor : node->neighbors)
{
dfs(neighbor);
map[node]->neighbors.push_back(map[neighbor]);
}
unordered_map<Node *, Node *> m;
return helper(node, m);
}
public:
UndirectedGraphNode *cloneGraph(UndirectedGraphNode *node)
Node *helper(Node *node, unordered_map<Node *, Node *> &m)
{
if (!node)
return node;
dfs(node);
return map[node];
return NULL;
if (m.count(node))
return m[node];
Node *clone = new Node(node->val);
m[node] = clone;
for (Node *neighbor : node->neighbors)
{
clone->neighbors.push_back(helper(neighbor, m));
}
return clone;
}
};
\ No newline at end of file
};
......@@ -73,7 +73,30 @@
## aop
### before
```cpp
#include <bits/stdc++.h>
using namespace std;
class Node
{
public:
int val;
vector<Node *> neighbors;
Node()
{
val = 0;
neighbors = vector<Node *>();
}
Node(int _val)
{
val = _val;
neighbors = vector<Node *>();
}
Node(int _val, vector<Node *> _neighbors)
{
val = _val;
neighbors = _neighbors;
}
};
```
### after
```cpp
......@@ -82,21 +105,120 @@
## 答案
```cpp
class Solution
{
public:
unordered_map<Node *, Node *> ump;
Node *cloneGraph(Node *node)
{
if (node == nullptr)
return node;
if (ump.find(node) == ump.end())
return ump[node];
Node *new_node = new Node(node->val);
ump[node] = new_node;
for (auto &n : node->neighbors)
{
new_node->neighbors.emplace_back(cloneGraph(n));
}
return new_node;
}
};
```
## 选项
### A
```cpp
class Solution
{
public:
Node *cloneGraph(Node *node)
{
if (node == NULL)
return nullptr;
queue<Node *> q;
map<Node *, Node *> visit;
q.push(node);
Node *newNode;
while (!q.empty())
{
Node *now = q.front();
q.pop();
newNode = new Node(now->val);
visit[now] = newNode;
for (auto x : now->neighbors)
{
if (!visit.count(x))
{
q.push(x);
}
}
}
int i = 0;
for (auto x : visit)
{
Node *now = x.first;
for (auto y : now->neighbors)
{
x.second->neighbors.push_back(visit[y]);
}
}
return visit.find(node)->second;
}
};
```
### B
```cpp
class Solution
{
public:
map<int, Node *> list;
Node *cloneGraph(Node *node)
{
if (node == NULL)
return NULL;
Node *new_node = new Node(node->val, vector<Node *>(node->neighbors.size(), NULL));
list.insert(map<int, Node *>::value_type(new_node->val, new_node));
for (int i = 0; i < new_node->neighbors.size(); i++)
{
if (list.count(node->neighbors[i]->val) > 0)
new_node->neighbors[i] = list[node->neighbors[i]->val];
else
new_node->neighbors[i] = cloneGraph(node->neighbors[i]);
}
return new_node;
}
};
```
### C
```cpp
class Solution
{
public:
Node *cloneGraph(Node *node)
{
unordered_map<Node *, Node *> m;
return helper(node, m);
}
Node *helper(Node *node, unordered_map<Node *, Node *> &m)
{
if (!node)
return NULL;
if (m.count(node))
return m[node];
Node *clone = new Node(node->val);
m[node] = clone;
for (Node *neighbor : node->neighbors)
{
clone->neighbors.push_back(helper(neighbor, m));
}
return clone;
}
};
```
......@@ -76,7 +76,8 @@
## aop
### before
```cpp
#include <bits/stdc++.h>
using namespace std;
```
### after
```cpp
......@@ -85,21 +86,187 @@
## 答案
```cpp
class Solution
{
public:
int evalRPN(vector<string> &tokens)
{
stack<int> stk;
int n = tokens.size();
for (int i = 0; i < n; i++)
{
string token = tokens[i];
if (isNumber(token))
{
stk.push(atoi(token.c_str()));
}
else
{
int num2 = stk.top();
int num1 = stk.top();
switch (token[0])
{
case '+':
stk.push(num1 + num2);
break;
case '-':
stk.push(num1 - num2);
break;
case '*':
stk.push(num1 * num2);
break;
case '/':
stk.push(num1 / num2);
break;
}
}
}
return stk.top();
}
bool isNumber(string token)
{
return !(token == "+" || token == "-" || token == "*" || token == "/");
}
};
```
## 选项
### A
```cpp
class Solution
{
public:
int isNumber(string s)
{
return !(s == "+" || s == "-" || s == "*" || s == "/");
}
int evalRPN(vector<string> &tokens)
{
stack<int> stk;
int len = tokens.size();
for (int i = 0; i < len; ++i)
{
string str = tokens[i];
if (isNumber(str))
{
stk.push(atoi(str.c_str()));
}
else
{
int a = stk.top();
stk.pop();
int b = stk.top();
stk.pop();
switch (str[0])
{
case '+':
stk.push(b + a);
break;
case '-':
stk.push(b - a);
break;
case '*':
stk.push(b * a);
break;
case '/':
stk.push(b / a);
break;
}
}
}
return stk.top();
}
};
```
### B
```cpp
class Solution
{
public:
int evalRPN(vector<string> &tokens)
{
stack<int> sp;
int n = tokens.size();
for (int i = 0; i < n; i++)
{
if (tokens[i] == "+")
{
int x = sp.top();
sp.pop();
int y = sp.top();
sp.pop();
sp.push(x + y);
}
else if (tokens[i] == "-")
{
int x = sp.top();
sp.pop();
int y = sp.top();
sp.pop();
sp.push(y - x);
}
else if (tokens[i] == "*")
{
int x = sp.top();
sp.pop();
int y = sp.top();
sp.pop();
sp.push(x * y);
}
else if (tokens[i] == "/")
{
int x = sp.top();
sp.pop();
int y = sp.top();
sp.pop();
sp.push(y / x);
}
else
{
sp.push(stoi(tokens[i]));
}
}
return sp.top();
}
};
```
### C
```cpp
class Solution
{
public:
int evalRPN(vector<string> &tokens)
{
stack<int> num;
for (int i = 0; i < tokens.size(); ++i)
{
if (tokens[i] == "+" || tokens[i] == "-" || tokens[i] == "*" || tokens[i] == "/")
{
int j;
int a = num.top();
num.pop();
int b = num.top();
num.pop();
if (tokens[i] == "+")
j = b + a;
else if (tokens[i] == "-")
j = b - a;
else if (tokens[i] == "*")
j = b * a;
else
j = b / a;
num.push(j);
}
else
{
num.push(stoi(tokens[i]));
}
}
return num.top();
}
};
```
#include <bits/stdc++.h>
using namespace std;
class Solution
{
public:
vector<int> findOrder(int numCourses, vector<vector<int>> &prerequisites)
{
vector<int> result;
vector<int> fake;
vector<int> degree(numCourses, 0);
unordered_map<int, vector<int>> map;
for (vector<int> prerequisite : prerequisites)
{
map[prerequisite[1]].push_back(prerequisite[0]);
degree[prerequisite[0]]++;
}
queue<int> q;
for (int i = 0; i < numCourses; i++)
{
if (degree[i] == 0)
{
q.push(i);
}
}
while (!q.empty())
{
int cur = q.front();
result.push_back(cur);
q.pop();
for (int next : map[cur])
{
degree[next]--;
if (degree[next] == 0)
q.push(next);
}
}
return result.size() == numCourses ? result : fake;
}
};
\ No newline at end of file
......@@ -60,7 +60,8 @@
## aop
### before
```cpp
#include <bits/stdc++.h>
using namespace std;
```
### after
```cpp
......@@ -69,21 +70,205 @@
## 答案
```cpp
class Solution
{
public:
vector<int> findOrder(int numCourses, vector<pair<int, int>> &prerequisites)
{
vector<int> heads(numCourses, -1), degree(numCourses, 0), points, args;
pair<int, int> p;
vector<int> ans;
int from, to, count = 0, len = prerequisites.size();
for (int i = 0; i < len; ++i)
{
p = prerequisites[i];
from = p.second;
to = p.first;
args.push_back(heads[from]);
points.push_back(to);
heads[from] = count++;
}
queue<int> q;
for (int i = 0; i < numCourses; ++i)
if (degree[i] == 0)
{
q.push(i);
ans.push_back(i);
}
while (!q.empty())
{
from = q.front();
q.pop();
to = heads[from];
while (to != -1)
{
if (--degree[points[to]] == 0)
{
q.push(points[to]);
ans.push_back(points[to]);
}
to = args[to];
}
}
for (int i = 0; i < numCourses; ++i)
if (degree[i] > 0)
return vector<int>();
return ans;
}
};
```
## 选项
### A
```cpp
class Solution
{
public:
vector<int> findOrder(int numCourses, vector<vector<int>> &prerequisites)
{
int n = numCourses;
vector<unordered_set<int>> g(n);
vector<int> m(n);
for (auto &e : prerequisites)
{
int i = e[0], j = e[1];
g[j].insert(i), m[i]++;
}
queue<int> q;
auto f = [&](int i)
{
if (!m[i])
q.push(i);
};
for (int i = 0; i < n; i++)
f(i);
vector<int> res;
while (n--)
{
if (q.empty())
return {};
int i = q.front();
q.pop();
res.push_back(i);
for (int j : g[i])
m[j]--, f(j);
}
return res;
}
};
```
### B
```cpp
class Solution
{
private:
vector<vector<int>> edges;
vector<int> visited;
vector<int> result;
bool invalid;
public:
void dfs(int u)
{
visited[u] = 1;
for (int v : edges[u])
{
if (visited[v] == 0)
{
dfs(v);
if (invalid)
{
return;
}
}
else if (visited[v] == 1)
{
invalid = true;
return;
}
}
visited[u] = 2;
result.push_back(u);
}
vector<int> findOrder(int numCourses, vector<vector<int>> &prerequisites)
{
edges.resize(numCourses);
visited.resize(numCourses);
for (const auto &info : prerequisites)
{
edges[info[1]].push_back(info[0]);
}
for (int i = 0; i < numCourses && !invalid; ++i)
{
if (!visited[i])
{
dfs(i);
}
}
if (invalid)
{
return {};
}
reverse(result.begin(), result.end());
return result;
}
};
```
### C
```cpp
class Solution
{
public:
vector<int> findOrder(int numCourses, vector<vector<int>> &prerequisites)
{
vector<int> result;
vector<int> fake;
vector<int> degree(numCourses, 0);
unordered_map<int, vector<int>> map;
for (vector<int> prerequisite : prerequisites)
{
map[prerequisite[1]].push_back(prerequisite[0]);
degree[prerequisite[0]]++;
}
queue<int> q;
for (int i = 0; i < numCourses; i++)
{
if (degree[i] == 0)
{
q.push(i);
}
}
while (!q.empty())
{
int cur = q.front();
result.push_back(cur);
q.pop();
for (int next : map[cur])
{
degree[next]--;
if (degree[next] == 0)
q.push(next);
}
}
return result.size() == numCourses ? result : fake;
}
};
```
......@@ -55,21 +55,159 @@
## 答案
```cpp
class Solution
{
public:
vector<vector<int>> getSkyline(vector<vector<int>> &buildings)
{
if (buildings.empty())
return {};
multiset<pair<int, int>> st;
for (auto b : buildings)
{
st.insert(make_pair(b[0], -b[2]));
st.insert(make_pair(b[1], b[2]));
}
vector<vector<int>> ret;
multiset<int> height = {0};
int m = 0;
for (auto s : st)
{
if (s.second < 0)
height.insert(-s.second);
else
height.erase(height.find(s.second));
if (m != *height.rbegin())
ret.push_back({s.first, *height.rbegin()});
}
return ret;
}
};
```
## 选项
### A
```cpp
class Solution
{
public:
vector<vector<int>> getSkyline(vector<vector<int>> &buildings)
{
vector<pair<int, int>> h;
multiset<int> m;
vector<vector<int>> res;
for (const auto &b : buildings)
{
h.push_back({b[0], -b[2]});
h.push_back({b[1], b[2]});
}
sort(h.begin(), h.end());
int prev = 0, cur = 0;
m.insert(0);
for (auto i : h)
{
if (i.second < 0)
m.insert(-i.second);
else
m.erase(m.find(i.second));
cur = *m.rbegin();
if (cur != prev)
{
res.push_back({i.first, cur});
prev = cur;
}
}
return res;
}
};
```
### B
```cpp
class Solution
{
public:
vector<vector<int>> getSkyline(vector<vector<int>> &buildings)
{
multiset<pair<int, int>> all;
vector<vector<int>> res;
for (auto &e : buildings)
{
all.insert(make_pair(e[0], -e[2]));
all.insert(make_pair(e[1], e[2]));
}
multiset<int> heights({0});
vector<int> last = {0, 0};
for (auto &e : all)
{
e.second < 0 ? heights.insert(-e.second) : heights.erase(heights.find(e.second));
auto max_height = *heights.rbegin();
if (last[1] != max_height)
{
last[0] = e.first;
last[1] = max_height;
res.push_back(last);
}
}
return res;
}
};
```
### C
```cpp
class Solution
{
public:
vector<vector<int>> getSkyline(vector<vector<int>> &buildings)
{
multiset<pair<int, int>> all;
vector<vector<int>> res;
for (auto &e : buildings)
{
all.insert(make_pair(e[0], -e[2]));
all.insert(make_pair(e[1], e[2]));
}
multiset<int> heights;
heights.insert(0);
vector<int> last;
last.push_back(0);
last.push_back(0);
for (auto &p : all)
{
if (p.second < 0)
heights.insert(-p.second);
else
heights.erase(heights.find(p.second));
auto maxHeight = *heights.rbegin();
if (last[1] != maxHeight)
{
last[0] = p.first;
last[1] = maxHeight;
res.push_back(last);
}
}
return res;
}
};
```
class Solution
{
public:
static constexpr int dirs[4][2] = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}};
int m, n;
int longestIncreasingPath(vector<vector<int>> &matrix)
{
if (matrix.size() == 0 || matrix[0].size() == 0)
{
return 0;
}
m = matrix.size();
n = matrix[0].size();
int res = 0;
auto memo = vector<vector<int>>(m, vector<int>(n, 0));
for (int i = 0; i < m; ++i)
{
for (int j = 0; j < n; ++j)
{
if (memo[i][j])
res = max(res, memo[i][j]);
else
res = max(res, dfs(i, j, matrix, memo));
}
}
return res;
}
int dfs(int i, int j, vector<vector<int>> &matrix, vector<vector<int>> &memo)
{
int temp = 1;
for (int k = 0; k < 4; ++k)
{
int x = i + dirs[k][0];
int y = j + dirs[k][1];
if ((x >= 0) && (x < m) && (y >= 0) && (y < n) && (matrix[i][j] < matrix[x][y]))
{
if (memo[x][y])
temp = max(temp, memo[x][y] + 1);
else
temp = max(temp, dfs(x, y, matrix, memo) + 1);
}
}
memo[i][j] = temp;
return temp;
}
};
......@@ -42,7 +42,8 @@
## aop
### before
```cpp
#include <bits/stdc++.h>
using namespace std;
```
### after
```cpp
......@@ -51,21 +52,198 @@
## 答案
```cpp
class Solution
{
public:
int m, n;
vector<vector<int>> memo;
int dfs(vector<vector<int>> &matrix, int x, int y)
{
if (memo[x][y] != -1)
return memo[x][y];
int ret = 1;
if (x > 0 && matrix[x - 1][y] > matrix[x][y])
ret = max(ret, 1 + dfs(matrix, x - 1, y - 1));
if (x < m - 1 && matrix[x + 1][y] > matrix[x][y])
ret = max(ret, 1 + dfs(matrix, x + 1, y + 1));
if (y > 0 && matrix[x][y - 1] > matrix[x][y])
ret = max(ret, 1 + dfs(matrix, x, y - 1));
if (y < n - 1 && matrix[x][y + 1] > matrix[x][y])
ret = max(ret, 1 + dfs(matrix, x, y + 1));
memo[x][y] = ret;
return ret;
}
int longestIncreasingPath(vector<vector<int>> &matrix)
{
m = matrix.size();
if (m == 0)
return 0;
n = matrix[0].size();
memo.resize(m);
int ans = 1;
for (int i = 0; i < m; ++i)
memo[i].resize(n, -1);
for (int i = 0; i < m; ++i)
{
for (int j = 0; j < n; ++j)
{
int temp = dfs(matrix, i, j);
ans = ans < temp ? temp : ans;
}
}
return ans;
}
};
```
## 选项
### A
```cpp
class Solution
{
public:
vector<vector<int>> state = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}};
int longestIncreasingPath(vector<vector<int>> &matrix)
{
int n = matrix.size();
if (n == 0)
return 0;
int m = matrix[0].size();
vector<vector<int>> dp(n, vector<int>(m, 0));
int res = 0;
for (int i = 0; i < n; i++)
for (int j = 0; j < m; j++)
res = max(dfs(dp, matrix, i, j), res);
return res;
}
int dfs(vector<vector<int>> &dp, vector<vector<int>> matrix, int i, int j)
{
if (dp[i][j] != 0)
return dp[i][j];
dp[i][j] = 1;
for (vector<int> s : state)
{
int x = i + s[0];
int y = j + s[1];
if (x >= 0 && x < matrix.size() && y >= 0 && y < matrix[0].size() && matrix[i][j] < matrix[x][y])
dp[i][j] = max(dp[i][j], dfs(dp, matrix, x, y) + 1);
}
return dp[i][j];
}
};
```
### B
```cpp
class Solution
{
public:
vector<vector<int>> use;
int dfs(int i, int j, vector<vector<int>> &matrix, int m, int n)
{
int len = 1, size, ans = 0;
if (i - 1 >= 0 && matrix[i - 1][j] > matrix[i][j])
{
if (use[i - 1][j] == 0)
len = max(len, dfs(i - 1, j, matrix, m, n) + 1);
else
len = max(len, use[i - 1][j] + 1);
}
if (j - 1 >= 0 && matrix[i][j - 1] > matrix[i][j])
{
if (use[i][j - 1] == 0)
len = max(len, dfs(i, j - 1, matrix, m, n) + 1);
else
len = max(len, use[i][j - 1] + 1);
}
if (i + 1 < m && matrix[i + 1][j] > matrix[i][j])
{
if (use[i + 1][j] == 0)
len = max(len, dfs(i + 1, j, matrix, m, n) + 1);
else
len = max(len, use[i + 1][j] + 1);
}
if (j + 1 < n && matrix[i][j + 1] > matrix[i][j])
{
if (use[i][j + 1] == 0)
len = max(len, dfs(i, j + 1, matrix, m, n) + 1);
else
len = max(len, use[i][j + 1] + 1);
}
use[i][j] = len;
return len;
}
int longestIncreasingPath(vector<vector<int>> &matrix)
{
if (matrix.empty() || matrix[0].empty())
return 0;
int m = matrix.size(), n = matrix[0].size();
use = vector(m, vector<int>(n, 0));
int i, j;
int ans = 0;
for (int i = 0; i < m; i++)
{
for (int j = 0; j < n; j++)
{
if (!use[i][j])
ans = max(ans, dfs(i, j, matrix, m, n));
}
}
return ans;
}
};
```
### C
```cpp
```
class Solution
{
public:
static constexpr int dirs[4][2] = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}};
int m, n;
int longestIncreasingPath(vector<vector<int>> &matrix)
{
if (matrix.size() == 0 || matrix[0].size() == 0)
{
return 0;
}
m = matrix.size();
n = matrix[0].size();
int res = 0;
auto memo = vector<vector<int>>(m, vector<int>(n, 0));
for (int i = 0; i < m; ++i)
{
for (int j = 0; j < n; ++j)
{
if (memo[i][j])
res = max(res, memo[i][j]);
else
res = max(res, dfs(i, j, matrix, memo));
}
}
return res;
}
int dfs(int i, int j, vector<vector<int>> &matrix, vector<vector<int>> &memo)
{
int temp = 1;
for (int k = 0; k < 4; ++k)
{
int x = i + dirs[k][0];
int y = j + dirs[k][1];
if ((x >= 0) && (x < m) && (y >= 0) && (y < n) && (matrix[i][j] < matrix[x][y]))
{
if (memo[x][y])
temp = max(temp, memo[x][y] + 1);
else
temp = max(temp, dfs(x, y, matrix, memo) + 1);
}
}
memo[i][j] = temp;
return temp;
}
};
```
\ No newline at end of file
......@@ -43,7 +43,8 @@
## aop
### before
```cpp
#include <bits/stdc++.h>
using namespace std;
```
### after
```cpp
......@@ -52,21 +53,213 @@
## 答案
```cpp
unordered_map<int, string> rev;
int cmp(pair<int, int> x, pair<int, int> y)
{
return rev[x.first] < rev[y.first];
}
class Solution
{
public:
unordered_map<string, int> mp;
int cnt = 0;
int head[10005], nex[10005], to[10005], tot = 0;
int vis[10005];
vector<string> ans;
void add(int x, int y)
{
to[++tot] = y;
nex[tot] = head[x];
head[x] = tot;
}
void euler(int x)
{
vector<pair<int, int>> vec;
for (int i = head[x]; i; i = nex[i])
{
int v = to[i];
if (vis[i])
{
continue;
}
vec.push_back({v, i});
}
sort(vec.begin(), vec.end(), cmp);
for (int i = 0; i < vec.size(); i++)
{
if (vis[vec[i].second])
continue;
vis[vec[i].second] = 1;
euler(vec[i].first);
ans.push_back(rev[vec[i].first]);
}
}
vector<string> findItinerary(vector<vector<string>> &tickets)
{
mp["JFK"] = 1;
rev[1] = "JFK";
cnt = 1;
for (int i = 0; i < tickets.size(); i++)
{
string s1 = tickets[i][0], s2 = tickets[i][1];
if (mp[s1])
{
mp[s1] = ++cnt;
rev[cnt] = s1;
}
if (mp[s2])
{
mp[s2] = ++cnt;
rev[cnt] = s2;
}
add(mp[s1], mp[s2]);
}
euler(1);
ans.push_back(rev[1]);
reverse(ans.begin(), ans.end());
return ans;
}
};
```
## 选项
### A
```cpp
class Solution
{
public:
vector<string> ans;
unordered_map<string, vector<string>> ticket;
unordered_map<string, vector<int>> use;
bool dfs(string &now, int begin, int n)
{
if (begin == n)
{
return true;
}
else
{
int size = ticket[now].size();
for (int i = 0; i < size; i++)
{
if (!use[now][i])
{
ans.push_back(ticket[now][i]);
use[now][i] = 1;
if (dfs(ticket[now][i], begin + 1, n))
return true;
ans.pop_back();
use[now][i] = 0;
}
}
}
return false;
}
vector<string> findItinerary(vector<vector<string>> &tickets)
{
int n = tickets.size();
for (int i = 0; i < n; i++)
{
int j, n = ticket[tickets[i][0]].size();
for (j = 0; j < n; j++)
if (ticket[tickets[i][0]][j] >= tickets[i][1])
break;
ticket[tickets[i][0]].insert(ticket[tickets[i][0]].begin() + j, tickets[i][1]);
use[tickets[i][0]].push_back(0);
}
string beginC = "JFK";
ans.push_back(beginC);
dfs(beginC, 0, n);
return ans;
}
};
```
### B
```cpp
class Solution
{
unordered_map<string, multiset<string>> m;
vector<string> ans;
public:
vector<string> findItinerary(vector<vector<string>> &tickets)
{
for (auto &t : tickets)
m[t[0]].insert(t[1]);
dfs("JFK");
reverse(ans.begin(), ans.end());
return ans;
}
void dfs(string s)
{
while (m[s].size() != 0)
{
string to = *m[s].begin();
m[s].erase(m[s].begin());
dfs(to);
}
ans.push_back(s);
}
};
```
### C
```cpp
class Solution
{
public:
struct cmp
{
bool operator()(const string &a, const string &b)
{
return a > b;
}
};
vector<string> findItinerary(vector<pair<string, string>> tickets)
{
map<string, int> m;
vector<priority_queue<string, vector<string>, cmp>> queues;
for (auto p : tickets)
{
if (m.find(p.first) == m.end())
{
priority_queue<string, vector<string>, cmp> newQueue;
newQueue.push(p.second);
queues.push_back(newQueue);
m.insert(make_pair(p.first, queues.size() - 1));
}
else
{
queues[m[p.first]].push(p.second);
}
}
vector<string> ans;
stack<string> visitedPlaces;
visitedPlaces.push("JFK");
while (!visitedPlaces.empty())
{
string current = visitedPlaces.top();
if (m.find(current) == m.end() || queues[m[current]].size() == 0)
{
ans.push_back(current);
visitedPlaces.pop();
}
else
{
visitedPlaces.push(queues[m[current]].top());
queues[m[current]].pop();
}
}
reverse(ans.begin(), ans.end());
return ans;
}
};
```
......@@ -4,7 +4,18 @@
## aop
### before
```cpp
#include <bits/stdc++.h>
using namespace std;
struct TreeNode
{
int val;
TreeNode *left;
TreeNode *right;
TreeNode() : val(0), left(nullptr), right(nullptr) {}
TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
};
```
### after
```cpp
......@@ -13,21 +24,111 @@
## 答案
```cpp
class Solution
{
public:
vector<int> inorderTraversal(TreeNode *root)
{
vector<int> result;
return InorderTraversal(root, result);
}
private:
vector<int> InorderTraversal(TreeNode *root, vector<int> &result)
{
if (root == NULL)
return result;
InorderTraversal(root->left, result);
InorderTraversal(root->right, result);
result.push_back(root->val);
return result;
}
};
```
## 选项
### A
```cpp
class Solution
{
public:
vector<int> inorderTraversal(TreeNode *root)
{
vector<int> res;
stack<TreeNode *> s;
while (root != nullptr || !s.empty())
{
if (root != nullptr)
{
s.push(root);
root = root->left;
}
else
{
auto cur = s.top();
s.pop();
res.emplace_back(cur->val);
root = cur->right;
}
}
return res;
}
};
```
### B
```cpp
class Solution
{
public:
vector<int> inorderTraversal(TreeNode *root)
{
vector<int> ret;
stack<TreeNode *> toTraversal;
while (root != NULL || !toTraversal.empty())
{
while (root != NULL)
{
toTraversal.push(root);
root = root->left;
}
root = toTraversal.top();
toTraversal.pop();
ret.push_back(root->val);
root = root->right;
}
return ret;
}
};
```
### C
```cpp
class Solution
{
private:
void rec(TreeNode *root, vector<int> &ret)
{
if (root != NULL)
{
rec(root->left, ret);
ret.push_back(root->val);
rec(root->right, ret);
}
}
public:
vector<int> postorderTraversal(TreeNode *root)
{
vector<int> ret;
rec(root, ret);
return ret;
}
};
```
......@@ -35,7 +35,18 @@
## aop
### before
```cpp
#include <bits/stdc++.h>
using namespace std;
struct TreeNode
{
int val;
TreeNode *left;
TreeNode *right;
TreeNode() : val(0), left(nullptr), right(nullptr) {}
TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
};
```
### after
```cpp
......@@ -44,21 +55,173 @@
## 答案
```cpp
class Solution
{
public:
vector<TreeNode *> generateTrees(int n)
{
if (n <= 0)
return vector<TreeNode *>{};
return generate(1, n);
}
vector<TreeNode *> generate(int begin, int end)
{
vector<TreeNode *> ret;
if (begin > end)
{
return ret;
}
for (int i = begin; i <= end; ++i)
{
vector<TreeNode *> lSubs = generate(begin, i - 1);
vector<TreeNode *> rSubs = generate(i + 1, end);
for (auto l : lSubs)
{
for (auto r : rSubs)
{
TreeNode *root = new TreeNode(i);
root->left = l;
root->right = r;
ret.push_back(cloneTree(root));
}
}
}
return ret;
}
};
```
## 选项
### A
```cpp
class Solution
{
public:
vector<TreeNode *> generateTrees(int n)
{
vector<TreeNode *> res;
if (n < 1)
return res;
res = creatTree(1, n);
return res;
}
vector<TreeNode *> creatTree(int start, int end)
{
vector<TreeNode *> res;
if (start > end)
{
res.push_back(NULL);
return res;
}
if (start == end)
{
TreeNode *node = new TreeNode(start);
res.push_back(node);
return res;
}
for (int i = start; i <= end; i++)
{
vector<TreeNode *> left = creatTree(start, i - 1);
vector<TreeNode *> right = creatTree(i + 1, end);
for (int j = 0; j < left.size(); j++)
{
for (int k = 0; k < right.size(); k++)
{
TreeNode *node = new TreeNode(i);
node->left = left[j];
node->right = right[k];
res.push_back(node);
}
}
}
return res;
}
};
```
### B
```cpp
class Solution
{
public:
vector<TreeNode *> m[9][9];
vector<TreeNode *> generate(int left, int right)
{
if (left > right)
return {nullptr};
if (!m[left][right].empty())
return m[left][right];
vector<TreeNode *> trees;
for (int i = left; i <= right; i++)
{
vector<TreeNode *> left_all = generate(left, i - 1);
vector<TreeNode *> right_all = generate(i + 1, right);
for (TreeNode *l : left_all)
{
for (TreeNode *r : right_all)
{
TreeNode *root = new TreeNode(i);
root->left = l;
root->right = r;
trees.emplace_back(root);
}
}
}
m[left][right] = trees;
return trees;
}
vector<TreeNode *> generateTrees(int n)
{
return generate(1, n);
}
};
```
### C
```cpp
class Solution
{
public:
vector<TreeNode *> generateTrees(int n)
{
vector<TreeNode *> res;
if (n == 0)
{
return res;
}
return gem(1, n);
}
vector<TreeNode *> gem(int start, int end)
{
vector<TreeNode *> res;
if (start > end)
{
res.push_back(NULL);
}
for (int i = start; i <= end; i++)
{
vector<TreeNode *> lefts = gem(start, i - 1);
vector<TreeNode *> rights = gem(i + 1, end);
for (auto left : lefts)
{
for (auto right : rights)
{
TreeNode *temp = new TreeNode(i);
temp->left = left;
temp->right = right;
res.push_back(temp);
}
}
}
return res;
}
};
```
......@@ -30,7 +30,8 @@
## aop
### before
```cpp
#include <bits/stdc++.h>
using namespace std;
```
### after
```cpp
......@@ -39,21 +40,109 @@
## 答案
```cpp
class Solution
{
public:
int numTrees(int n)
{
if (n < 1)
{
return 0;
}
return numTrees(1, n);
}
int numTrees(int begin, int end)
{
if (begin > end)
{
return 1;
}
int sum = 0;
for (int i = begin; i <= end; i++)
{
int left = numTrees(begin, i);
int right = numTrees(i + 1, end);
sum += left * right;
}
return sum;
}
};
```
## 选项
### A
```cpp
class Solution
{
public:
int numTrees(int n)
{
if (n < 2)
return 1;
else if (n == 3)
return 5;
else if (n == 4)
return 14;
else if (n == 5)
return 42;
else
{
int i, sum = 0, left, right;
for (i = 0; i < n; i++)
{
left = i;
right = n - i - 1;
sum += numTrees(left) * numTrees(right);
}
return sum;
}
}
};
```
### B
```cpp
class Solution
{
public:
int numTrees(int n)
{
if (n < 2)
return 1;
else
{
int i, sum = 0, left, right;
for (i = 0; i < n; i++)
{
left = i;
right = n - i - 1;
sum += numTrees(left) * numTrees(right);
}
return sum;
}
}
};
```
### C
```cpp
class Solution
{
public:
int numTrees(int n)
{
int dp[n + 1];
memset(dp, 0, sizeof(dp));
dp[0] = dp[1] = 1;
for (int i = 2; i <= n; ++i)
{
for (int j = 0; j < i; ++j)
{
dp[i] += dp[j] * dp[i - j - 1];
}
}
return dp[n];
}
};
```
......@@ -38,7 +38,18 @@
## aop
### before
```cpp
#include <bits/stdc++.h>
using namespace std;
struct TreeNode
{
int val;
TreeNode *left;
TreeNode *right;
TreeNode() : val(0), left(nullptr), right(nullptr) {}
TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
};
```
### after
```cpp
......@@ -47,21 +58,106 @@
## 答案
```cpp
class Solution
{
public:
bool judge(TreeNode *root, long start, long end)
{
if (!root)
return true;
if (start >= root->val || end <= root->val)
return false;
return judge(root->left, start, root->val);
}
bool isValidBST(TreeNode *root)
{
long start = INT_MIN - 1;
long end = INT_MAX + 1;
return judge(root, start, end);
}
};
```
## 选项
### A
```cpp
class Solution
{
public:
TreeNode *pre;
bool isValidBST(TreeNode *root)
{
if (!root)
return true;
if (!isValidBST(root->left))
return false;
if (pre && pre->val >= root->val)
return false;
pre = root;
if (!isValidBST(root->right))
return false;
return true;
}
};
```
### B
```cpp
class Solution
{
public:
void midorder(TreeNode *root, vector<int> &arr)
{
if (root)
{
midorder(root->left, arr);
arr.push_back(root->val);
midorder(root->right, arr);
}
}
bool isValidBST(TreeNode *root)
{
vector<int> arr;
midorder(root, arr);
for (int i = 1; i < arr.size(); i++)
{
if (arr[i] <= arr[i - 1])
return false;
}
return true;
}
};
```
### C
```cpp
class Solution
{
public:
bool isValidBST(TreeNode *root)
{
if (root)
{
long long f = -0x3f3f3f3f3f3f;
return dfs(root, f);
}
else
return true;
}
bool dfs(TreeNode *root, long long &f_val)
{
bool res = true;
if (root)
{
res &= dfs(root->left, f_val) && (root->val > f_val);
if (!res)
return false;
f_val = root->val;
res &= dfs(root->right, f_val);
}
return res;
}
};
```
{
"node_id": "569d5e11c4fc5de7844053d9a733c5e8",
"keywords": [
"leetcode",
"逆波兰表达式求值"
],
"children": [],
"export": [
"solution.json"
],
"title": "逆波兰表达式求值"
}
\ No newline at end of file
<p>根据<a href="https://baike.baidu.com/item/%E9%80%86%E6%B3%A2%E5%85%B0%E5%BC%8F/128437" target="_blank"> 逆波兰表示法</a>,求表达式的值。</p>
<p>有效的算符包括 <code>+</code><code>-</code><code>*</code><code>/</code> 。每个运算对象可以是整数,也可以是另一个逆波兰表达式。</p>
<p> </p>
<p><strong>说明:</strong></p>
<ul>
<li>整数除法只保留整数部分。</li>
<li>给定逆波兰表达式总是有效的。换句话说,表达式总会得出有效数值且不存在除数为 0 的情况。</li>
</ul>
<p> </p>
<p><strong>示例 1:</strong></p>
<pre>
<strong>输入:</strong>tokens = ["2","1","+","3","*"]
<strong>输出:</strong>9
<strong>解释:</strong>该算式转化为常见的中缀算术表达式为:((2 + 1) * 3) = 9
</pre>
<p><strong>示例 2:</strong></p>
<pre>
<strong>输入:</strong>tokens = ["4","13","5","/","+"]
<strong>输出:</strong>6
<strong>解释:</strong>该算式转化为常见的中缀算术表达式为:(4 + (13 / 5)) = 6
</pre>
<p><strong>示例 3:</strong></p>
<pre>
<strong>输入:</strong>tokens = ["10","6","9","3","+","-11","*","/","*","17","+","5","+"]
<strong>输出:</strong>22
<strong>解释:</strong>
该算式转化为常见的中缀算术表达式为:
((10 * (6 / ((9 + 3) * -11))) + 17) + 5
= ((10 * (6 / (12 * -11))) + 17) + 5
= ((10 * (6 / -132)) + 17) + 5
= ((10 * 0) + 17) + 5
= (0 + 17) + 5
= 17 + 5
= 22</pre>
<p> </p>
<p><strong>提示:</strong></p>
<ul>
<li><code>1 <= tokens.length <= 10<sup>4</sup></code></li>
<li><code>tokens[i]</code> 要么是一个算符(<code>"+"</code><code>"-"</code><code>"*"</code><code>"/"</code>),要么是一个在范围 <code>[-200, 200]</code> 内的整数</li>
</ul>
<p> </p>
<p><strong>逆波兰表达式:</strong></p>
<p>逆波兰表达式是一种后缀表达式,所谓后缀就是指算符写在后面。</p>
<ul>
<li>平常使用的算式则是一种中缀表达式,如 <code>( 1 + 2 ) * ( 3 + 4 )</code></li>
<li>该算式的逆波兰表达式写法为 <code>( ( 1 2 + ) ( 3 4 + ) * )</code></li>
</ul>
<p>逆波兰表达式主要有以下两个优点:</p>
<ul>
<li>去掉括号后表达式无歧义,上式即便写成 <code>1 2 + 3 4 + * </code>也可以依据次序计算出正确结果。</li>
<li>适合用栈操作运算:遇到数字则入栈;遇到算符则取出栈顶两个数字进行计算,并将结果压入栈中。</li>
</ul>
int evalRPN(vector<string> &tokens)
{
stack<int> sp;
int n = tokens.size();
for (int i = 0; i < n; i++)
{
if (tokens[i] == "+")
{
int x = sp.top();
sp.pop();
int y = sp.top();
sp.pop();
sp.push(x + y);
}
else if (tokens[i] == "-")
{
int x = sp.top();
sp.pop();
int y = sp.top();
sp.pop();
sp.push(y - x);
}
else if (tokens[i] == "*")
{
int x = sp.top();
sp.pop();
int y = sp.top();
sp.pop();
sp.push(x * y);
}
else if (tokens[i] == "/")
{
int x = sp.top();
sp.pop();
int y = sp.top();
sp.pop();
sp.push(y / x);
}
else
{
sp.push(stoi(tokens[i]));
}
}
return sp.top();
}
{
"type": "code_options",
"author": "CSDN.net",
"source": "solution.md",
"exercise_id": "98426a6a4a264cd2bd95ed3efc14f748"
}
\ No newline at end of file
# 逆波兰表达式求值
<p>根据<a href="https://baike.baidu.com/item/%E9%80%86%E6%B3%A2%E5%85%B0%E5%BC%8F/128437" target="_blank"> 逆波兰表示法</a>,求表达式的值。</p>
<p>有效的算符包括 <code>+</code><code>-</code><code>*</code><code>/</code> 。每个运算对象可以是整数,也可以是另一个逆波兰表达式。</p>
<p> </p>
<p><strong>说明:</strong></p>
<ul>
<li>整数除法只保留整数部分。</li>
<li>给定逆波兰表达式总是有效的。换句话说,表达式总会得出有效数值且不存在除数为 0 的情况。</li>
</ul>
<p> </p>
<p><strong>示例 1:</strong></p>
<pre>
<strong>输入:</strong>tokens = ["2","1","+","3","*"]
<strong>输出:</strong>9
<strong>解释:</strong>该算式转化为常见的中缀算术表达式为:((2 + 1) * 3) = 9
</pre>
<p><strong>示例 2:</strong></p>
<pre>
<strong>输入:</strong>tokens = ["4","13","5","/","+"]
<strong>输出:</strong>6
<strong>解释:</strong>该算式转化为常见的中缀算术表达式为:(4 + (13 / 5)) = 6
</pre>
<p><strong>示例 3:</strong></p>
<pre>
<strong>输入:</strong>tokens = ["10","6","9","3","+","-11","*","/","*","17","+","5","+"]
<strong>输出:</strong>22
<strong>解释:</strong>
该算式转化为常见的中缀算术表达式为:
((10 * (6 / ((9 + 3) * -11))) + 17) + 5
= ((10 * (6 / (12 * -11))) + 17) + 5
= ((10 * (6 / -132)) + 17) + 5
= ((10 * 0) + 17) + 5
= (0 + 17) + 5
= 17 + 5
= 22</pre>
<p> </p>
<p><strong>提示:</strong></p>
<ul>
<li><code>1 <= tokens.length <= 10<sup>4</sup></code></li>
<li><code>tokens[i]</code> 要么是一个算符(<code>"+"</code><code>"-"</code><code>"*"</code><code>"/"</code>),要么是一个在范围 <code>[-200, 200]</code> 内的整数</li>
</ul>
<p> </p>
<p><strong>逆波兰表达式:</strong></p>
<p>逆波兰表达式是一种后缀表达式,所谓后缀就是指算符写在后面。</p>
<ul>
<li>平常使用的算式则是一种中缀表达式,如 <code>( 1 + 2 ) * ( 3 + 4 )</code></li>
<li>该算式的逆波兰表达式写法为 <code>( ( 1 2 + ) ( 3 4 + ) * )</code></li>
</ul>
<p>逆波兰表达式主要有以下两个优点:</p>
<ul>
<li>去掉括号后表达式无歧义,上式即便写成 <code>1 2 + 3 4 + * </code>也可以依据次序计算出正确结果。</li>
<li>适合用栈操作运算:遇到数字则入栈;遇到算符则取出栈顶两个数字进行计算,并将结果压入栈中。</li>
</ul>
<p>以下错误的选项是?</p>
## aop
### before
```cpp
#include <bits/stdc++.h>
using namespace std;
```
### after
```cpp
```
## 答案
```cpp
class Solution
{
public:
int evalRPN(vector<string> &tokens)
{
stack<int> stk;
int n = tokens.size();
for (int i = 0; i < n; i++)
{
string token = tokens[i];
if (isNumber(token))
{
stk.push(atoi(token.c_str()));
}
else
{
int num2 = stk.top();
int num1 = stk.top();
switch (token[0])
{
case '+':
stk.push(num1 + num2);
break;
case '-':
stk.push(num1 - num2);
break;
case '*':
stk.push(num1 * num2);
break;
case '/':
stk.push(num1 / num2);
break;
}
}
}
return stk.top();
}
bool isNumber(string token)
{
return !(token == "+" || token == "-" || token == "*" || token == "/");
}
};
```
## 选项
### A
```cpp
class Solution
{
public:
int isNumber(string s)
{
return !(s == "+" || s == "-" || s == "*" || s == "/");
}
int evalRPN(vector<string> &tokens)
{
stack<int> stk;
int len = tokens.size();
for (int i = 0; i < len; ++i)
{
string str = tokens[i];
if (isNumber(str))
{
stk.push(atoi(str.c_str()));
}
else
{
int a = stk.top();
stk.pop();
int b = stk.top();
stk.pop();
switch (str[0])
{
case '+':
stk.push(b + a);
break;
case '-':
stk.push(b - a);
break;
case '*':
stk.push(b * a);
break;
case '/':
stk.push(b / a);
break;
}
}
}
return stk.top();
}
};
```
### B
```cpp
class Solution
{
public:
int evalRPN(vector<string> &tokens)
{
stack<int> sp;
int n = tokens.size();
for (int i = 0; i < n; i++)
{
if (tokens[i] == "+")
{
int x = sp.top();
sp.pop();
int y = sp.top();
sp.pop();
sp.push(x + y);
}
else if (tokens[i] == "-")
{
int x = sp.top();
sp.pop();
int y = sp.top();
sp.pop();
sp.push(y - x);
}
else if (tokens[i] == "*")
{
int x = sp.top();
sp.pop();
int y = sp.top();
sp.pop();
sp.push(x * y);
}
else if (tokens[i] == "/")
{
int x = sp.top();
sp.pop();
int y = sp.top();
sp.pop();
sp.push(y / x);
}
else
{
sp.push(stoi(tokens[i]));
}
}
return sp.top();
}
};
```
### C
```cpp
class Solution
{
public:
int evalRPN(vector<string> &tokens)
{
stack<int> num;
for (int i = 0; i < tokens.size(); ++i)
{
if (tokens[i] == "+" || tokens[i] == "-" || tokens[i] == "*" || tokens[i] == "/")
{
int j;
int a = num.top();
num.pop();
int b = num.top();
num.pop();
if (tokens[i] == "+")
j = b + a;
else if (tokens[i] == "-")
j = b - a;
else if (tokens[i] == "*")
j = b * a;
else
j = b / a;
num.push(j);
}
else
{
num.push(stoi(tokens[i]));
}
}
return num.top();
}
};
```
{
"node_id": "569d5e11c4fc5de7844053d9a733c5e8",
"keywords": [
"leetcode",
"天际线问题"
],
"children": [],
"export": [
"solution.json"
],
"title": "天际线问题"
}
\ No newline at end of file
<p>城市的天际线是从远处观看该城市中所有建筑物形成的轮廓的外部轮廓。给你所有建筑物的位置和高度,请返回由这些建筑物形成的<strong> 天际线</strong></p>
<p>每个建筑物的几何信息由数组 <code>buildings</code> 表示,其中三元组 <code>buildings[i] = [lefti, righti, heighti]</code> 表示:</p>
<ul>
<li><code>left<sub>i</sub></code> 是第 <code>i</code> 座建筑物左边缘的 <code>x</code> 坐标。</li>
<li><code>right<sub>i</sub></code> 是第 <code>i</code> 座建筑物右边缘的 <code>x</code> 坐标。</li>
<li><code>height<sub>i</sub></code> 是第 <code>i</code> 座建筑物的高度。</li>
</ul>
<p><strong>天际线</strong> 应该表示为由 “关键点” 组成的列表,格式 <code>[[x<sub>1</sub>,y<sub>1</sub>],[x<sub>2</sub>,y<sub>2</sub>],...]</code> ,并按 <strong>x 坐标 </strong>进行 <strong>排序</strong><strong>关键点是水平线段的左端点</strong>。列表中最后一个点是最右侧建筑物的终点,<code>y</code> 坐标始终为 <code>0</code> ,仅用于标记天际线的终点。此外,任何两个相邻建筑物之间的地面都应被视为天际线轮廓的一部分。</p>
<p><strong>注意:</strong>输出天际线中不得有连续的相同高度的水平线。例如 <code>[...[2 3], [4 5], [7 5], [11 5], [12 7]...]</code> 是不正确的答案;三条高度为 5 的线应该在最终输出中合并为一个:<code>[...[2 3], [4 5], [12 7], ...]</code></p>
<p> </p>
<p><strong>示例 1:</strong></p>
<img alt="" src="https://assets.leetcode.com/uploads/2020/12/01/merged.jpg" style="width: 800px; height: 331px;" />
<pre>
<strong>输入:</strong>buildings = [[2,9,10],[3,7,15],[5,12,12],[15,20,10],[19,24,8]]
<strong>输出:</strong>[[2,10],[3,15],[7,12],[12,0],[15,10],[20,8],[24,0]]
<strong>解释:</strong>
图 A<strong> </strong>显示输入的所有建筑物的位置和高度,
图 B 显示由这些建筑物形成的天际线。图 B 中的红点表示输出列表中的关键点。</pre>
<p><strong>示例 2:</strong></p>
<pre>
<strong>输入:</strong>buildings = [[0,2,3],[2,5,3]]
<strong>输出:</strong>[[0,3],[5,0]]
</pre>
<p> </p>
<p><strong>提示:</strong></p>
<ul>
<li><code>1 <= buildings.length <= 10<sup>4</sup></code></li>
<li><code>0 <= left<sub>i</sub> < right<sub>i</sub> <= 2<sup>31</sup> - 1</code></li>
<li><code>1 <= height<sub>i</sub> <= 2<sup>31</sup> - 1</code></li>
<li><code>buildings</code><code>left<sub>i</sub></code> 非递减排序</li>
</ul>
{
"type": "code_options",
"author": "CSDN.net",
"source": "solution.md",
"exercise_id": "179d9a777c8440db8d82b9550027f55e"
}
\ No newline at end of file
# 天际线问题
<p>城市的天际线是从远处观看该城市中所有建筑物形成的轮廓的外部轮廓。给你所有建筑物的位置和高度,请返回由这些建筑物形成的<strong> 天际线</strong></p>
<p>每个建筑物的几何信息由数组 <code>buildings</code> 表示,其中三元组 <code>buildings[i] = [lefti, righti, heighti]</code> 表示:</p>
<ul>
<li><code>left<sub>i</sub></code> 是第 <code>i</code> 座建筑物左边缘的 <code>x</code> 坐标。</li>
<li><code>right<sub>i</sub></code> 是第 <code>i</code> 座建筑物右边缘的 <code>x</code> 坐标。</li>
<li><code>height<sub>i</sub></code> 是第 <code>i</code> 座建筑物的高度。</li>
</ul>
<p><strong>天际线</strong> 应该表示为由 “关键点” 组成的列表,格式 <code>[[x<sub>1</sub>,y<sub>1</sub>],[x<sub>2</sub>,y<sub>2</sub>],...]</code> ,并按 <strong>x 坐标 </strong>进行 <strong>排序</strong><strong>关键点是水平线段的左端点</strong>。列表中最后一个点是最右侧建筑物的终点,<code>y</code> 坐标始终为 <code>0</code> ,仅用于标记天际线的终点。此外,任何两个相邻建筑物之间的地面都应被视为天际线轮廓的一部分。</p>
<p><strong>注意:</strong>输出天际线中不得有连续的相同高度的水平线。例如 <code>[...[2 3], [4 5], [7 5], [11 5], [12 7]...]</code> 是不正确的答案;三条高度为 5 的线应该在最终输出中合并为一个:<code>[...[2 3], [4 5], [12 7], ...]</code></p>
<p> </p>
<p><strong>示例 1:</strong></p>
<img alt="" src="https://assets.leetcode.com/uploads/2020/12/01/merged.jpg" style="width: 800px; height: 331px;" />
<pre>
<strong>输入:</strong>buildings = [[2,9,10],[3,7,15],[5,12,12],[15,20,10],[19,24,8]]
<strong>输出:</strong>[[2,10],[3,15],[7,12],[12,0],[15,10],[20,8],[24,0]]
<strong>解释:</strong>
图 A<strong> </strong>显示输入的所有建筑物的位置和高度,
图 B 显示由这些建筑物形成的天际线。图 B 中的红点表示输出列表中的关键点。</pre>
<p><strong>示例 2:</strong></p>
<pre>
<strong>输入:</strong>buildings = [[0,2,3],[2,5,3]]
<strong>输出:</strong>[[0,3],[5,0]]
</pre>
<p> </p>
<p><strong>提示:</strong></p>
<ul>
<li><code>1 <= buildings.length <= 10<sup>4</sup></code></li>
<li><code>0 <= left<sub>i</sub> < right<sub>i</sub> <= 2<sup>31</sup> - 1</code></li>
<li><code>1 <= height<sub>i</sub> <= 2<sup>31</sup> - 1</code></li>
<li><code>buildings</code><code>left<sub>i</sub></code> 非递减排序</li>
</ul>
<p>以下错误的选项是?</p>
## aop
### before
```cpp
```
### after
```cpp
```
## 答案
```cpp
class Solution
{
public:
vector<vector<int>> getSkyline(vector<vector<int>> &buildings)
{
if (buildings.empty())
return {};
multiset<pair<int, int>> st;
for (auto b : buildings)
{
st.insert(make_pair(b[0], -b[2]));
st.insert(make_pair(b[1], b[2]));
}
vector<vector<int>> ret;
multiset<int> height = {0};
int m = 0;
for (auto s : st)
{
if (s.second < 0)
height.insert(-s.second);
else
height.erase(height.find(s.second));
if (m != *height.rbegin())
ret.push_back({s.first, *height.rbegin()});
}
return ret;
}
};
```
## 选项
### A
```cpp
class Solution
{
public:
vector<vector<int>> getSkyline(vector<vector<int>> &buildings)
{
vector<pair<int, int>> h;
multiset<int> m;
vector<vector<int>> res;
for (const auto &b : buildings)
{
h.push_back({b[0], -b[2]});
h.push_back({b[1], b[2]});
}
sort(h.begin(), h.end());
int prev = 0, cur = 0;
m.insert(0);
for (auto i : h)
{
if (i.second < 0)
m.insert(-i.second);
else
m.erase(m.find(i.second));
cur = *m.rbegin();
if (cur != prev)
{
res.push_back({i.first, cur});
prev = cur;
}
}
return res;
}
};
```
### B
```cpp
class Solution
{
public:
vector<vector<int>> getSkyline(vector<vector<int>> &buildings)
{
multiset<pair<int, int>> all;
vector<vector<int>> res;
for (auto &e : buildings)
{
all.insert(make_pair(e[0], -e[2]));
all.insert(make_pair(e[1], e[2]));
}
multiset<int> heights({0});
vector<int> last = {0, 0};
for (auto &e : all)
{
e.second < 0 ? heights.insert(-e.second) : heights.erase(heights.find(e.second));
auto max_height = *heights.rbegin();
if (last[1] != max_height)
{
last[0] = e.first;
last[1] = max_height;
res.push_back(last);
}
}
return res;
}
};
```
### C
```cpp
class Solution
{
public:
vector<vector<int>> getSkyline(vector<vector<int>> &buildings)
{
multiset<pair<int, int>> all;
vector<vector<int>> res;
for (auto &e : buildings)
{
all.insert(make_pair(e[0], -e[2]));
all.insert(make_pair(e[1], e[2]));
}
multiset<int> heights;
heights.insert(0);
vector<int> last;
last.push_back(0);
last.push_back(0);
for (auto &p : all)
{
if (p.second < 0)
heights.insert(-p.second);
else
heights.erase(heights.find(p.second));
auto maxHeight = *heights.rbegin();
if (last[1] != maxHeight)
{
last[0] = p.first;
last[1] = maxHeight;
res.push_back(last);
}
}
return res;
}
};
```
{
"node_id": "569d5e11c4fc5de7844053d9a733c5e8",
"keywords": [
"leetcode",
"二叉树中的最大路径和"
],
"children": [],
"export": [
"solution.json"
],
"title": "二叉树中的最大路径和"
}
\ No newline at end of file
<p><strong>路径</strong> 被定义为一条从树中任意节点出发,沿父节点-子节点连接,达到任意节点的序列。同一个节点在一条路径序列中 <strong>至多出现一次</strong> 。该路径<strong> 至少包含一个 </strong>节点,且不一定经过根节点。</p>
<p><strong>路径和</strong> 是路径中各节点值的总和。</p>
<p>给你一个二叉树的根节点 <code>root</code> ,返回其 <strong>最大路径和</strong></p>
<p> </p>
<p><strong>示例 1:</strong></p>
<img alt="" src="https://assets.leetcode.com/uploads/2020/10/13/exx1.jpg" style="width: 322px; height: 182px;" />
<pre>
<strong>输入:</strong>root = [1,2,3]
<strong>输出:</strong>6
<strong>解释:</strong>最优路径是 2 -> 1 -> 3 ,路径和为 2 + 1 + 3 = 6</pre>
<p><strong>示例 2:</strong></p>
<img alt="" src="https://assets.leetcode.com/uploads/2020/10/13/exx2.jpg" />
<pre>
<strong>输入:</strong>root = [-10,9,20,null,null,15,7]
<strong>输出:</strong>42
<strong>解释:</strong>最优路径是 15 -> 20 -> 7 ,路径和为 15 + 20 + 7 = 42
</pre>
<p> </p>
<p><strong>提示:</strong></p>
<ul>
<li>树中节点数目范围是 <code>[1, 3 * 10<sup>4</sup>]</code></li>
<li><code>-1000 <= Node.val <= 1000</code></li>
</ul>
#include <cstddef>
#include <algorithm>
struct TreeNode
{
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
class Solution
{
int maxPathSum(TreeNode *root, int &maxSum)
{
if (!root)
return 0;
int leftMax = std::max(0, maxPathSum(root->left, maxSum));
int rightMax = std::max(0, maxPathSum(root->right, maxSum));
maxSum = std::max(maxSum, leftMax + rightMax + root->val);
return root->val + std::max(leftMax, rightMax);
}
public:
int maxPathSum(TreeNode *root)
{
int maxSum = INT_MIN;
maxPathSum(root, maxSum);
return maxSum;
}
};
\ No newline at end of file
{
"type": "code_options",
"author": "CSDN.net",
"source": "solution.md",
"exercise_id": "b26b38cc4631496080fc88639e010df3"
}
\ No newline at end of file
# 二叉树中的最大路径和
<p><strong>路径</strong> 被定义为一条从树中任意节点出发,沿父节点-子节点连接,达到任意节点的序列。同一个节点在一条路径序列中 <strong>至多出现一次</strong> 。该路径<strong> 至少包含一个 </strong>节点,且不一定经过根节点。</p>
<p><strong>路径和</strong> 是路径中各节点值的总和。</p>
<p>给你一个二叉树的根节点 <code>root</code> ,返回其 <strong>最大路径和</strong></p>
<p> </p>
<p><strong>示例 1:</strong></p>
<img alt="" src="https://assets.leetcode.com/uploads/2020/10/13/exx1.jpg" style="width: 322px; height: 182px;" />
<pre>
<strong>输入:</strong>root = [1,2,3]
<strong>输出:</strong>6
<strong>解释:</strong>最优路径是 2 -> 1 -> 3 ,路径和为 2 + 1 + 3 = 6</pre>
<p><strong>示例 2:</strong></p>
<img alt="" src="https://assets.leetcode.com/uploads/2020/10/13/exx2.jpg" />
<pre>
<strong>输入:</strong>root = [-10,9,20,null,null,15,7]
<strong>输出:</strong>42
<strong>解释:</strong>最优路径是 15 -> 20 -> 7 ,路径和为 15 + 20 + 7 = 42
</pre>
<p> </p>
<p><strong>提示:</strong></p>
<ul>
<li>树中节点数目范围是 <code>[1, 3 * 10<sup>4</sup>]</code></li>
<li><code>-1000 <= Node.val <= 1000</code></li>
</ul>
<p>以下错误的选项是?</p>
## aop
### before
```cpp
#include <bits/stdc++.h>
using namespace std;
struct TreeNode
{
int val;
TreeNode *left;
TreeNode *right;
TreeNode() : val(0), left(nullptr), right(nullptr) {}
TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
};
```
### after
```cpp
```
## 答案
```cpp
class Solution
{
public:
int maxv = -123123632;
int maxPathSum(TreeNode *root)
{
if (root == NULL)
return 0;
calc(root);
return maxv;
}
int calc(TreeNode *root)
{
if (root == NULL)
return 0;
int temp = root->val;
int lmaxsum = calc(root->left);
int rmaxsum = calc(root->right);
if (lmaxsum > 0)
temp += lmaxsum;
if (rmaxsum > 0)
temp += rmaxsum;
return max(root->val, max(root->val + lmaxsum, root->val + rmaxsum));
}
};
```
## 选项
### A
```cpp
class Solution
{
int res = INT_MIN;
public:
int maxPathSum(TreeNode *root)
{
int p = getdfs(root);
return res;
}
int getdfs(TreeNode *node)
{
if (node == NULL)
return 0;
int left = max(getdfs(node->left), 0);
int right = max(getdfs(node->right), 0);
int size = left + right + node->val;
res = res > size ? res : size;
right = right > left ? right : left;
node->val = right + node->val;
return node->val;
}
};
```
### B
```cpp
class Solution
{
public:
int ans = 0;
int OneSideMax(TreeNode *root)
{
if (root == nullptr)
return 0;
int left = max(0, OneSideMax(root->left));
int right = max(0, OneSideMax(root->right));
ans = max(ans, left + right + root->val);
return max(left, right) + root->val;
}
int maxPathSum(TreeNode *root)
{
OneSideMax(root);
return ans;
}
};
```
### C
```cpp
class Solution
{
public:
int dfs(TreeNode *root, int &res)
{
if (root == NULL)
{
return 0;
}
int left = max(dfs(root->left, res), 0);
int right = max(dfs(root->right, res), 0);
res = max(res, root->val + left + right);
return root->val + max(left, right);
}
int maxPathSum(TreeNode *root)
{
int res = INT_MIN;
dfs(root, res);
return res;
}
};
```
{
"node_id": "569d5e11c4fc5de7844053d9a733c5e8",
"keywords": [
"leetcode",
"二叉树的中序遍历"
],
"children": [],
"export": [
"solution.json"
],
"title": "二叉树的中序遍历"
}
\ No newline at end of file
<p>给定一个二叉树的根节点 <code>root</code> ,返回它的 <strong>中序</strong> 遍历。</p><p> </p><p><strong>示例 1:</strong></p><img alt="" src="https://cdn.jsdelivr.net/gh/doocs/leetcode@main/solution/0000-0099/0094.Binary%20Tree%20Inorder%20Traversal/images/inorder_1.jpg" style="width: 202px; height: 324px;" /><pre><strong>输入:</strong>root = [1,null,2,3]<strong><br />输出:</strong>[1,3,2]</pre><p><strong>示例 2:</strong></p><pre><strong>输入:</strong>root = []<strong><br />输出:</strong>[]</pre><p><strong>示例 3:</strong></p><pre><strong>输入:</strong>root = [1]<strong><br />输出:</strong>[1]</pre><p><strong>示例 4:</strong></p><img alt="" src="https://cdn.jsdelivr.net/gh/doocs/leetcode@main/solution/0000-0099/0094.Binary%20Tree%20Inorder%20Traversal/images/inorder_5.jpg" style="width: 202px; height: 202px;" /><pre><strong>输入:</strong>root = [1,2]<strong><br />输出:</strong>[2,1]</pre><p><strong>示例 5:</strong></p><img alt="" src="https://cdn.jsdelivr.net/gh/doocs/leetcode@main/solution/0000-0099/0094.Binary%20Tree%20Inorder%20Traversal/images/inorder_4.jpg" style="width: 202px; height: 202px;" /><pre><strong>输入:</strong>root = [1,null,2]<strong><br />输出:</strong>[1,2]</pre><p> </p><p><strong>提示:</strong></p><ul> <li>树中节点数目在范围 <code>[0, 100]</code></li> <li><code>-100 <= Node.val <= 100</code></li></ul><p> </p><p><strong>进阶:</strong> 递归算法很简单,你可以通过迭代算法完成吗?</p>
\ No newline at end of file
#include <stdio.h>
#include <stdlib.h>
struct TreeNode
{
int val;
struct TreeNode *left;
struct TreeNode *right;
};
static void traverse(struct TreeNode *node, int *result, int *count)
{
if (node == NULL)
{
return;
}
traverse(node->left, result, count);
result[*count] = node->val;
(*count)++;
traverse(node->right, result, count);
}
static int *inorderTraversal(struct TreeNode *root, int *returnSize)
{
if (root == NULL)
{
*returnSize = 0;
return NULL;
}
int count = 0;
int *result = malloc(5000 * sizeof(int));
traverse(root, result, &count);
*returnSize = count;
return result;
}
int main()
{
int count = 0;
inorderTraversal(NULL, &count);
return 0;
}
\ No newline at end of file
{
"type": "code_options",
"author": "CSDN.net",
"source": "solution.md",
"exercise_id": "a02c10370c5d4f54ae54119aad298a2e"
}
\ No newline at end of file
# 二叉树的中序遍历
<p>给定一个二叉树的根节点 <code>root</code> ,返回它的 <strong>中序</strong> 遍历。</p><p> </p><p><strong>示例 1:</strong></p><img alt="" src="https://cdn.jsdelivr.net/gh/doocs/leetcode@main/solution/0000-0099/0094.Binary%20Tree%20Inorder%20Traversal/images/inorder_1.jpg" style="width: 202px; height: 324px;" /><pre><strong>输入:</strong>root = [1,null,2,3]<strong><br />输出:</strong>[1,3,2]</pre><p><strong>示例 2:</strong></p><pre><strong>输入:</strong>root = []<strong><br />输出:</strong>[]</pre><p><strong>示例 3:</strong></p><pre><strong>输入:</strong>root = [1]<strong><br />输出:</strong>[1]</pre><p><strong>示例 4:</strong></p><img alt="" src="https://cdn.jsdelivr.net/gh/doocs/leetcode@main/solution/0000-0099/0094.Binary%20Tree%20Inorder%20Traversal/images/inorder_5.jpg" style="width: 202px; height: 202px;" /><pre><strong>输入:</strong>root = [1,2]<strong><br />输出:</strong>[2,1]</pre><p><strong>示例 5:</strong></p><img alt="" src="https://cdn.jsdelivr.net/gh/doocs/leetcode@main/solution/0000-0099/0094.Binary%20Tree%20Inorder%20Traversal/images/inorder_4.jpg" style="width: 202px; height: 202px;" /><pre><strong>输入:</strong>root = [1,null,2]<strong><br />输出:</strong>[1,2]</pre><p> </p><p><strong>提示:</strong></p><ul> <li>树中节点数目在范围 <code>[0, 100]</code> 内</li> <li><code>-100 <= Node.val <= 100</code></li></ul><p> </p><p><strong>进阶:</strong> 递归算法很简单,你可以通过迭代算法完成吗?</p>
<p>以下错误的选项是?</p>
## aop
### before
```cpp
#include <bits/stdc++.h>
using namespace std;
struct TreeNode
{
int val;
TreeNode *left;
TreeNode *right;
TreeNode() : val(0), left(nullptr), right(nullptr) {}
TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
};
```
### after
```cpp
```
## 答案
```cpp
class Solution
{
public:
vector<int> inorderTraversal(TreeNode *root)
{
vector<int> result;
return InorderTraversal(root, result);
}
private:
vector<int> InorderTraversal(TreeNode *root, vector<int> &result)
{
if (root == NULL)
return result;
InorderTraversal(root->left, result);
InorderTraversal(root->right, result);
result.push_back(root->val);
return result;
}
};
```
## 选项
### A
```cpp
class Solution
{
public:
vector<int> inorderTraversal(TreeNode *root)
{
vector<int> res;
stack<TreeNode *> s;
while (root != nullptr || !s.empty())
{
if (root != nullptr)
{
s.push(root);
root = root->left;
}
else
{
auto cur = s.top();
s.pop();
res.emplace_back(cur->val);
root = cur->right;
}
}
return res;
}
};
```
### B
```cpp
class Solution
{
public:
vector<int> inorderTraversal(TreeNode *root)
{
vector<int> ret;
stack<TreeNode *> toTraversal;
while (root != NULL || !toTraversal.empty())
{
while (root != NULL)
{
toTraversal.push(root);
root = root->left;
}
root = toTraversal.top();
toTraversal.pop();
ret.push_back(root->val);
root = root->right;
}
return ret;
}
};
```
### C
```cpp
class Solution
{
private:
void rec(TreeNode *root, vector<int> &ret)
{
if (root != NULL)
{
rec(root->left, ret);
ret.push_back(root->val);
rec(root->right, ret);
}
}
public:
vector<int> postorderTraversal(TreeNode *root)
{
vector<int> ret;
rec(root, ret);
return ret;
}
};
```
{
"node_id": "569d5e11c4fc5de7844053d9a733c5e8",
"keywords": [
"leetcode",
"不同的二叉搜索树 II"
],
"children": [],
"export": [
"solution.json"
],
"title": "不同的二叉搜索树 II"
}
\ No newline at end of file
<div class="notranslate">
<p>给你一个整数 <code>n</code> ,请你生成并返回所有由 <code>n</code> 个节点组成且节点值从 <code>1</code><code>n</code> 互不相同的不同
<strong>二叉搜索树</strong><em> </em>。可以按 <strong>任意顺序</strong> 返回答案。
</p>
<p>&nbsp;</p>
<div class="original__bRMd">
<div>
<p><strong>示例 1:</strong></p>
<img style="width: 600px; height: 148px;"
src="https://assets.leetcode.com/uploads/2021/01/18/uniquebstn3.jpg" alt="">
<pre><strong>输入:</strong>n = 3
<strong><br />输出:</strong>[[1,null,2,null,3],[1,null,3,2],[2,1,3],[3,1,null,null,2],[3,2,null,1]]
</pre>
<p><strong>示例 2:</strong></p>
<pre><strong>输入:</strong>n = 1
<strong><br />输出:</strong>[[1]]
</pre>
<p>&nbsp;</p>
<p><strong>提示:</strong></p>
<ul>
<li><code>1 &lt;= n &lt;= 8</code></li>
</ul>
</div>
</div>
</div>
\ No newline at end of file
#include <stdio.h>
#include <stdlib.h>
struct TreeNode
{
int val;
struct TreeNode *left;
struct TreeNode *right;
};
static struct TreeNode *dfs(int low, int high, int *count)
{
int i, j, k;
if (low > high)
{
*count = 0;
return NULL;
}
else if (low == high)
{
struct TreeNode *node = malloc(sizeof(*node));
node->val = low;
node->left = NULL;
node->right = NULL;
*count = 1;
return node;
}
else
{
*count = 0;
int capacity = 5;
struct TreeNode *roots = malloc(capacity * sizeof(struct TreeNode));
for (i = low; i <= high; i++)
{
int left_cnt, right_cnt;
struct TreeNode *left_subs = dfs(low, i - 1, &left_cnt);
struct TreeNode *right_subs = dfs(i + 1, high, &right_cnt);
if (left_cnt == 0)
left_cnt = 1;
if (right_cnt == 0)
right_cnt = 1;
if (*count + (left_cnt * right_cnt) >= capacity)
{
capacity *= 2;
capacity += left_cnt * right_cnt;
roots = realloc(roots, capacity * sizeof(struct TreeNode));
}
for (j = 0; j < left_cnt; j++)
{
for (k = 0; k < right_cnt; k++)
{
roots[*count].val = i;
roots[*count].left = left_subs == NULL ? NULL : &left_subs[j];
roots[*count].right = right_subs == NULL ? NULL : &right_subs[k];
(*count)++;
}
}
}
return roots;
}
}
static struct TreeNode **generateTrees(int n, int *returnSize)
{
int i, count = 0;
struct TreeNode *roots = dfs(1, n, &count);
struct TreeNode **results = malloc(count * sizeof(struct TreeNode *));
for (i = 0; i < count; i++)
{
results[i] = &roots[i];
}
*returnSize = count;
return results;
}
static void dump(struct TreeNode *node)
{
printf("%d ", node->val);
if (node->left != NULL)
{
dump(node->left);
}
else
{
printf("# ");
}
if (node->right != NULL)
{
dump(node->right);
}
else
{
printf("# ");
}
}
int main(int argc, char **argv)
{
if (argc != 2)
{
fprintf(stderr, "Usage: ./test n\n");
exit(-1);
}
int i, count = 0;
struct TreeNode **results = generateTrees(atoi(argv[1]), &count);
for (i = 0; i < count; i++)
{
dump(results[i]);
printf("\n");
}
return 0;
}
\ No newline at end of file
{
"type": "code_options",
"author": "CSDN.net",
"source": "solution.md",
"exercise_id": "2714ff6cca444c66b461dc54a9a7af3f"
}
\ No newline at end of file
# 不同的二叉搜索树 II
<div class="notranslate">
<p>给你一个整数 <code>n</code> ,请你生成并返回所有由 <code>n</code> 个节点组成且节点值从 <code>1</code><code>n</code> 互不相同的不同
<strong>二叉搜索树</strong><em> </em>。可以按 <strong>任意顺序</strong> 返回答案。
</p>
<p>&nbsp;</p>
<div class="original__bRMd">
<div>
<p><strong>示例 1:</strong></p>
<img style="width: 600px; height: 148px;"
src="https://assets.leetcode.com/uploads/2021/01/18/uniquebstn3.jpg" alt="">
<pre><strong>输入:</strong>n = 3
<strong><br />输出:</strong>[[1,null,2,null,3],[1,null,3,2],[2,1,3],[3,1,null,null,2],[3,2,null,1]]
</pre>
<p><strong>示例 2:</strong></p>
<pre><strong>输入:</strong>n = 1
<strong><br />输出:</strong>[[1]]
</pre>
<p>&nbsp;</p>
<p><strong>提示:</strong></p>
<ul>
<li><code>1 &lt;= n &lt;= 8</code></li>
</ul>
</div>
</div>
</div>
<p>以下错误的选项是?</p>
## aop
### before
```cpp
#include <bits/stdc++.h>
using namespace std;
struct TreeNode
{
int val;
TreeNode *left;
TreeNode *right;
TreeNode() : val(0), left(nullptr), right(nullptr) {}
TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
};
```
### after
```cpp
```
## 答案
```cpp
class Solution
{
public:
vector<TreeNode *> generateTrees(int n)
{
if (n <= 0)
return vector<TreeNode *>{};
return generate(1, n);
}
vector<TreeNode *> generate(int begin, int end)
{
vector<TreeNode *> ret;
if (begin > end)
{
return ret;
}
for (int i = begin; i <= end; ++i)
{
vector<TreeNode *> lSubs = generate(begin, i - 1);
vector<TreeNode *> rSubs = generate(i + 1, end);
for (auto l : lSubs)
{
for (auto r : rSubs)
{
TreeNode *root = new TreeNode(i);
root->left = l;
root->right = r;
ret.push_back(cloneTree(root));
}
}
}
return ret;
}
};
```
## 选项
### A
```cpp
class Solution
{
public:
vector<TreeNode *> generateTrees(int n)
{
vector<TreeNode *> res;
if (n < 1)
return res;
res = creatTree(1, n);
return res;
}
vector<TreeNode *> creatTree(int start, int end)
{
vector<TreeNode *> res;
if (start > end)
{
res.push_back(NULL);
return res;
}
if (start == end)
{
TreeNode *node = new TreeNode(start);
res.push_back(node);
return res;
}
for (int i = start; i <= end; i++)
{
vector<TreeNode *> left = creatTree(start, i - 1);
vector<TreeNode *> right = creatTree(i + 1, end);
for (int j = 0; j < left.size(); j++)
{
for (int k = 0; k < right.size(); k++)
{
TreeNode *node = new TreeNode(i);
node->left = left[j];
node->right = right[k];
res.push_back(node);
}
}
}
return res;
}
};
```
### B
```cpp
class Solution
{
public:
vector<TreeNode *> m[9][9];
vector<TreeNode *> generate(int left, int right)
{
if (left > right)
return {nullptr};
if (!m[left][right].empty())
return m[left][right];
vector<TreeNode *> trees;
for (int i = left; i <= right; i++)
{
vector<TreeNode *> left_all = generate(left, i - 1);
vector<TreeNode *> right_all = generate(i + 1, right);
for (TreeNode *l : left_all)
{
for (TreeNode *r : right_all)
{
TreeNode *root = new TreeNode(i);
root->left = l;
root->right = r;
trees.emplace_back(root);
}
}
}
m[left][right] = trees;
return trees;
}
vector<TreeNode *> generateTrees(int n)
{
return generate(1, n);
}
};
```
### C
```cpp
class Solution
{
public:
vector<TreeNode *> generateTrees(int n)
{
vector<TreeNode *> res;
if (n == 0)
{
return res;
}
return gem(1, n);
}
vector<TreeNode *> gem(int start, int end)
{
vector<TreeNode *> res;
if (start > end)
{
res.push_back(NULL);
}
for (int i = start; i <= end; i++)
{
vector<TreeNode *> lefts = gem(start, i - 1);
vector<TreeNode *> rights = gem(i + 1, end);
for (auto left : lefts)
{
for (auto right : rights)
{
TreeNode *temp = new TreeNode(i);
temp->left = left;
temp->right = right;
res.push_back(temp);
}
}
}
return res;
}
};
```
{
"node_id": "569d5e11c4fc5de7844053d9a733c5e8",
"keywords": [
"leetcode",
"不同的二叉搜索树"
],
"children": [],
"export": [
"solution.json"
],
"title": "不同的二叉搜索树"
}
\ No newline at end of file
<div class="notranslate">
<p>给你一个整数 <code>n</code> ,求恰由 <code>n</code> 个节点组成且节点值从 <code>1</code><code>n</code> 互不相同的 <strong>二叉搜索树</strong>
有多少种?返回满足题意的二叉搜索树的种数。</p>
<p>&nbsp;</p>
<p><strong>示例 1:</strong></p>
<img style="width: 600px; height: 148px;" src="https://assets.leetcode.com/uploads/2021/01/18/uniquebstn3.jpg"
alt="">
<pre><strong>输入:</strong>n = 3
<strong><br />输出:</strong>5
</pre>
<p><strong>示例 2:</strong></p>
<pre><strong>输入:</strong>n = 1
<strong><br />输出:</strong>1
</pre>
<p>&nbsp;</p>
<p><strong>提示:</strong></p>
<ul>
<li><code>1 &lt;= n &lt;= 19</code></li>
</ul>
</div>
\ No newline at end of file
#include <stdc++.h>
using namespace std;
class Solution
{
public:
int numTrees(int n)
{
vector<int> sum(n + 1);
sum[0] = 1;
for (int i = 1; i <= n; i++)
{
for (int j = 0; j < i; j++)
{
sum[i] += sum[j] * sum[i - j - 1];
}
}
return sum[n];
}
}
\ No newline at end of file
{
"type": "code_options",
"author": "CSDN.net",
"source": "solution.md",
"exercise_id": "31d913cae4a4447f9dec393dd398d4fb"
}
\ No newline at end of file
# 不同的二叉搜索树
<div class="notranslate">
<p>给你一个整数 <code>n</code> ,求恰由 <code>n</code> 个节点组成且节点值从 <code>1</code><code>n</code> 互不相同的 <strong>二叉搜索树</strong>
有多少种?返回满足题意的二叉搜索树的种数。</p>
<p>&nbsp;</p>
<p><strong>示例 1:</strong></p>
<img style="width: 600px; height: 148px;" src="https://assets.leetcode.com/uploads/2021/01/18/uniquebstn3.jpg"
alt="">
<pre><strong>输入:</strong>n = 3
<strong><br />输出:</strong>5
</pre>
<p><strong>示例 2:</strong></p>
<pre><strong>输入:</strong>n = 1
<strong><br />输出:</strong>1
</pre>
<p>&nbsp;</p>
<p><strong>提示:</strong></p>
<ul>
<li><code>1 &lt;= n &lt;= 19</code></li>
</ul>
</div>
<p>以下错误的选项是?</p>
## aop
### before
```cpp
#include <bits/stdc++.h>
using namespace std;
```
### after
```cpp
```
## 答案
```cpp
class Solution
{
public:
int numTrees(int n)
{
if (n < 1)
{
return 0;
}
return numTrees(1, n);
}
int numTrees(int begin, int end)
{
if (begin > end)
{
return 1;
}
int sum = 0;
for (int i = begin; i <= end; i++)
{
int left = numTrees(begin, i);
int right = numTrees(i + 1, end);
sum += left * right;
}
return sum;
}
};
```
## 选项
### A
```cpp
class Solution
{
public:
int numTrees(int n)
{
if (n < 2)
return 1;
else if (n == 3)
return 5;
else if (n == 4)
return 14;
else if (n == 5)
return 42;
else
{
int i, sum = 0, left, right;
for (i = 0; i < n; i++)
{
left = i;
right = n - i - 1;
sum += numTrees(left) * numTrees(right);
}
return sum;
}
}
};
```
### B
```cpp
class Solution
{
public:
int numTrees(int n)
{
if (n < 2)
return 1;
else
{
int i, sum = 0, left, right;
for (i = 0; i < n; i++)
{
left = i;
right = n - i - 1;
sum += numTrees(left) * numTrees(right);
}
return sum;
}
}
};
```
### C
```cpp
class Solution
{
public:
int numTrees(int n)
{
int dp[n + 1];
memset(dp, 0, sizeof(dp));
dp[0] = dp[1] = 1;
for (int i = 2; i <= n; ++i)
{
for (int j = 0; j < i; ++j)
{
dp[i] += dp[j] * dp[i - j - 1];
}
}
return dp[n];
}
};
```
{
"node_id": "569d5e11c4fc5de7844053d9a733c5e8",
"keywords": [
"leetcode",
"验证二叉搜索树"
],
"children": [],
"export": [
"solution.json"
],
"title": "验证二叉搜索树"
}
\ No newline at end of file
<div class="notranslate">
<p>给你一个二叉树的根节点 <code>root</code> ,判断其是否是一个有效的二叉搜索树。</p>
<p><strong>有效</strong> 二叉搜索树定义如下:</p>
<ul>
<li>节点的左子树只包含<strong> 小于 </strong>当前节点的数。</li>
<li>节点的右子树只包含 <strong>大于</strong> 当前节点的数。</li>
<li>所有左子树和右子树自身必须也是二叉搜索树。</li>
</ul>
<p>&nbsp;</p>
<p><strong>示例 1:</strong></p>
<img style="width: 302px; height: 182px;" src="https://assets.leetcode.com/uploads/2020/12/01/tree1.jpg" alt="">
<pre><strong>输入:</strong>root = [2,1,3]
<strong><br />输出:</strong>true
</pre>
<p><strong>示例 2:</strong></p>
<img style="width: 422px; height: 292px;" src="https://assets.leetcode.com/uploads/2020/12/01/tree2.jpg" alt="">
<pre><strong>输入:</strong>root = [5,1,4,null,null,3,6]
<strong><br />输出:</strong>false
<strong><br />解释:</strong>根节点的值是 5 ,但是右子节点的值是 4 。
</pre>
<p>&nbsp;</p>
<p><strong>提示:</strong></p>
<ul>
<li>树中节点数目范围在<code>[1, 10<sup>4</sup>]</code></li>
<li><code>-2<sup>31</sup> &lt;= Node.val &lt;= 2<sup>31</sup> - 1</code></li>
</ul>
</div>
\ No newline at end of file
#include <bits/stdc++.h>
using namespace std;
struct TreeNode
{
int val;
TreeNode *left;
TreeNode *right;
TreeNode() : val(0), left(nullptr), right(nullptr) {}
TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
};
class Solution
{
public:
bool isValidBST(TreeNode *root)
{
stack<TreeNode *> stk;
int prev = INT_MIN;
bool first = true;
while (!stk.empty() || root != nullptr)
{
if (root != nullptr)
{
stk.push(root);
root = root->left;
}
else
{
root = stk.top();
stk.pop();
if (!first && prev >= root->val)
{
return false;
}
first = false;
prev = root->val;
root = root->right;
}
}
return true;
}
};
\ No newline at end of file
{
"type": "code_options",
"author": "CSDN.net",
"source": "solution.md",
"exercise_id": "51cb9122d32c43f1a87b5c20e3f5a859"
}
\ No newline at end of file
# 验证二叉搜索树
<div class="notranslate">
<p>给你一个二叉树的根节点 <code>root</code> ,判断其是否是一个有效的二叉搜索树。</p>
<p><strong>有效</strong> 二叉搜索树定义如下:</p>
<ul>
<li>节点的左子树只包含<strong> 小于 </strong>当前节点的数。</li>
<li>节点的右子树只包含 <strong>大于</strong> 当前节点的数。</li>
<li>所有左子树和右子树自身必须也是二叉搜索树。</li>
</ul>
<p>&nbsp;</p>
<p><strong>示例 1:</strong></p>
<img style="width: 302px; height: 182px;" src="https://assets.leetcode.com/uploads/2020/12/01/tree1.jpg" alt="">
<pre><strong>输入:</strong>root = [2,1,3]
<strong><br />输出:</strong>true
</pre>
<p><strong>示例 2:</strong></p>
<img style="width: 422px; height: 292px;" src="https://assets.leetcode.com/uploads/2020/12/01/tree2.jpg" alt="">
<pre><strong>输入:</strong>root = [5,1,4,null,null,3,6]
<strong><br />输出:</strong>false
<strong><br />解释:</strong>根节点的值是 5 ,但是右子节点的值是 4 。
</pre>
<p>&nbsp;</p>
<p><strong>提示:</strong></p>
<ul>
<li>树中节点数目范围在<code>[1, 10<sup>4</sup>]</code> 内</li>
<li><code>-2<sup>31</sup> &lt;= Node.val &lt;= 2<sup>31</sup> - 1</code></li>
</ul>
</div>
<p>以下错误的选项是?</p>
## aop
### before
```cpp
#include <bits/stdc++.h>
using namespace std;
struct TreeNode
{
int val;
TreeNode *left;
TreeNode *right;
TreeNode() : val(0), left(nullptr), right(nullptr) {}
TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
};
```
### after
```cpp
```
## 答案
```cpp
class Solution
{
public:
bool judge(TreeNode *root, long start, long end)
{
if (!root)
return true;
if (start >= root->val || end <= root->val)
return false;
return judge(root->left, start, root->val);
}
bool isValidBST(TreeNode *root)
{
long start = INT_MIN - 1;
long end = INT_MAX + 1;
return judge(root, start, end);
}
};
```
## 选项
### A
```cpp
class Solution
{
public:
TreeNode *pre;
bool isValidBST(TreeNode *root)
{
if (!root)
return true;
if (!isValidBST(root->left))
return false;
if (pre && pre->val >= root->val)
return false;
pre = root;
if (!isValidBST(root->right))
return false;
return true;
}
};
```
### B
```cpp
class Solution
{
public:
void midorder(TreeNode *root, vector<int> &arr)
{
if (root)
{
midorder(root->left, arr);
arr.push_back(root->val);
midorder(root->right, arr);
}
}
bool isValidBST(TreeNode *root)
{
vector<int> arr;
midorder(root, arr);
for (int i = 1; i < arr.size(); i++)
{
if (arr[i] <= arr[i - 1])
return false;
}
return true;
}
};
```
### C
```cpp
class Solution
{
public:
bool isValidBST(TreeNode *root)
{
if (root)
{
long long f = -0x3f3f3f3f3f3f;
return dfs(root, f);
}
else
return true;
}
bool dfs(TreeNode *root, long long &f_val)
{
bool res = true;
if (root)
{
res &= dfs(root->left, f_val) && (root->val > f_val);
if (!res)
return false;
f_val = root->val;
res &= dfs(root->right, f_val);
}
return res;
}
};
```
{
"node_id": "569d5e11c4fc5de7844053d9a733c5e8",
"keywords": [
"leetcode",
"克隆图"
],
"children": [],
"export": [
"solution.json"
],
"title": "克隆图"
}
\ No newline at end of file
<p>给你无向&nbsp;<strong><a href="https://baike.baidu.com/item/连通图/6460995?fr=aladdin" target="_blank">连通</a>&nbsp;</strong>图中一个节点的引用,请你返回该图的&nbsp;<a href="https://baike.baidu.com/item/深拷贝/22785317?fr=aladdin" target="_blank"><strong>深拷贝</strong></a>(克隆)。</p>
<p>图中的每个节点都包含它的值 <code>val</code><code>int</code>) 和其邻居的列表(<code>list[Node]</code>)。</p>
<pre>class Node {
public int val;
public List&lt;Node&gt; neighbors;
}</pre>
<p>&nbsp;</p>
<p><strong>测试用例格式:</strong></p>
<p>简单起见,每个节点的值都和它的索引相同。例如,第一个节点值为 1(<code>val = 1</code>),第二个节点值为 2(<code>val = 2</code>),以此类推。该图在测试用例中使用邻接列表表示。</p>
<p><strong>邻接列表</strong> 是用于表示有限图的无序列表的集合。每个列表都描述了图中节点的邻居集。</p>
<p>给定节点将始终是图中的第一个节点(值为 1)。你必须将&nbsp;<strong>给定节点的拷贝&nbsp;</strong>作为对克隆图的引用返回。</p>
<p>&nbsp;</p>
<p><strong>示例 1:</strong></p>
<p><img alt="" src="https://assets.leetcode-cn.com/aliyun-lc-upload/uploads/2020/02/01/133_clone_graph_question.png" style="height: 500px; width: 500px;"></p>
<pre><strong>输入:</strong>adjList = [[2,4],[1,3],[2,4],[1,3]]
<strong>输出:</strong>[[2,4],[1,3],[2,4],[1,3]]
<strong>解释:
</strong>图中有 4 个节点。
节点 1 的值是 1,它有两个邻居:节点 2 和 4 。
节点 2 的值是 2,它有两个邻居:节点 1 和 3 。
节点 3 的值是 3,它有两个邻居:节点 2 和 4 。
节点 4 的值是 4,它有两个邻居:节点 1 和 3 。
</pre>
<p><strong>示例 2:</strong></p>
<p><img alt="" src="https://assets.leetcode-cn.com/aliyun-lc-upload/uploads/2020/02/01/graph.png" style="height: 148px; width: 163px;"></p>
<pre><strong>输入:</strong>adjList = [[]]
<strong>输出:</strong>[[]]
<strong>解释:</strong>输入包含一个空列表。该图仅仅只有一个值为 1 的节点,它没有任何邻居。
</pre>
<p><strong>示例 3:</strong></p>
<pre><strong>输入:</strong>adjList = []
<strong>输出:</strong>[]
<strong>解释:</strong>这个图是空的,它不含任何节点。
</pre>
<p><strong>示例 4:</strong></p>
<p><img alt="" src="https://assets.leetcode-cn.com/aliyun-lc-upload/uploads/2020/02/01/graph-1.png" style="height: 133px; width: 272px;"></p>
<pre><strong>输入:</strong>adjList = [[2],[1]]
<strong>输出:</strong>[[2],[1]]</pre>
<p>&nbsp;</p>
<p><strong>提示:</strong></p>
<ol>
<li>节点数不超过 100 。</li>
<li>每个节点值&nbsp;<code>Node.val</code> 都是唯一的,<code>1 &lt;= Node.val &lt;= 100</code></li>
<li>无向图是一个<a href="https://baike.baidu.com/item/简单图/1680528?fr=aladdin" target="_blank">简单图</a>,这意味着图中没有重复的边,也没有自环。</li>
<li>由于图是无向的,如果节点 <em>p</em> 是节点 <em>q</em> 的邻居,那么节点 <em>q</em> 也必须是节点 <em>p</em>&nbsp;的邻居。</li>
<li>图是连通图,你可以从给定节点访问到所有节点。</li>
</ol>
#include <bits/stdc++.h>
using namespace std;
class Node
{
public:
int val;
vector<Node *> neighbors;
Node()
{
val = 0;
neighbors = vector<Node *>();
}
Node(int _val)
{
val = _val;
neighbors = vector<Node *>();
}
Node(int _val, vector<Node *> _neighbors)
{
val = _val;
neighbors = _neighbors;
}
};
class Solution
{
public:
Node *cloneGraph(Node *node)
{
unordered_map<Node *, Node *> m;
return helper(node, m);
}
Node *helper(Node *node, unordered_map<Node *, Node *> &m)
{
if (!node)
return NULL;
if (m.count(node))
return m[node];
Node *clone = new Node(node->val);
m[node] = clone;
for (Node *neighbor : node->neighbors)
{
clone->neighbors.push_back(helper(neighbor, m));
}
return clone;
}
};
{
"type": "code_options",
"author": "CSDN.net",
"source": "solution.md",
"exercise_id": "03c1d93c7cbc4cb793ab90ad0fa6e0e1"
}
\ No newline at end of file
# 克隆图
<p>给你无向&nbsp;<strong><a href="https://baike.baidu.com/item/连通图/6460995?fr=aladdin" target="_blank">连通</a>&nbsp;</strong>图中一个节点的引用,请你返回该图的&nbsp;<a href="https://baike.baidu.com/item/深拷贝/22785317?fr=aladdin" target="_blank"><strong>深拷贝</strong></a>(克隆)。</p>
<p>图中的每个节点都包含它的值 <code>val</code><code>int</code>) 和其邻居的列表(<code>list[Node]</code>)。</p>
<pre>class Node {
public int val;
public List&lt;Node&gt; neighbors;
}</pre>
<p>&nbsp;</p>
<p><strong>测试用例格式:</strong></p>
<p>简单起见,每个节点的值都和它的索引相同。例如,第一个节点值为 1(<code>val = 1</code>),第二个节点值为 2(<code>val = 2</code>),以此类推。该图在测试用例中使用邻接列表表示。</p>
<p><strong>邻接列表</strong> 是用于表示有限图的无序列表的集合。每个列表都描述了图中节点的邻居集。</p>
<p>给定节点将始终是图中的第一个节点(值为 1)。你必须将&nbsp;<strong>给定节点的拷贝&nbsp;</strong>作为对克隆图的引用返回。</p>
<p>&nbsp;</p>
<p><strong>示例 1:</strong></p>
<p><img alt="" src="https://assets.leetcode-cn.com/aliyun-lc-upload/uploads/2020/02/01/133_clone_graph_question.png" style="height: 500px; width: 500px;"></p>
<pre><strong>输入:</strong>adjList = [[2,4],[1,3],[2,4],[1,3]]
<strong>输出:</strong>[[2,4],[1,3],[2,4],[1,3]]
<strong>解释:
</strong>图中有 4 个节点。
节点 1 的值是 1,它有两个邻居:节点 2 和 4 。
节点 2 的值是 2,它有两个邻居:节点 1 和 3 。
节点 3 的值是 3,它有两个邻居:节点 2 和 4 。
节点 4 的值是 4,它有两个邻居:节点 1 和 3 。
</pre>
<p><strong>示例 2:</strong></p>
<p><img alt="" src="https://assets.leetcode-cn.com/aliyun-lc-upload/uploads/2020/02/01/graph.png" style="height: 148px; width: 163px;"></p>
<pre><strong>输入:</strong>adjList = [[]]
<strong>输出:</strong>[[]]
<strong>解释:</strong>输入包含一个空列表。该图仅仅只有一个值为 1 的节点,它没有任何邻居。
</pre>
<p><strong>示例 3:</strong></p>
<pre><strong>输入:</strong>adjList = []
<strong>输出:</strong>[]
<strong>解释:</strong>这个图是空的,它不含任何节点。
</pre>
<p><strong>示例 4:</strong></p>
<p><img alt="" src="https://assets.leetcode-cn.com/aliyun-lc-upload/uploads/2020/02/01/graph-1.png" style="height: 133px; width: 272px;"></p>
<pre><strong>输入:</strong>adjList = [[2],[1]]
<strong>输出:</strong>[[2],[1]]</pre>
<p>&nbsp;</p>
<p><strong>提示:</strong></p>
<ol>
<li>节点数不超过 100 。</li>
<li>每个节点值&nbsp;<code>Node.val</code> 都是唯一的,<code>1 &lt;= Node.val &lt;= 100</code></li>
<li>无向图是一个<a href="https://baike.baidu.com/item/简单图/1680528?fr=aladdin" target="_blank">简单图</a>,这意味着图中没有重复的边,也没有自环。</li>
<li>由于图是无向的,如果节点 <em>p</em> 是节点 <em>q</em> 的邻居,那么节点 <em>q</em> 也必须是节点 <em>p</em>&nbsp;的邻居。</li>
<li>图是连通图,你可以从给定节点访问到所有节点。</li>
</ol>
<p>以下错误的选项是?</p>
## aop
### before
```cpp
#include <bits/stdc++.h>
using namespace std;
class Node
{
public:
int val;
vector<Node *> neighbors;
Node()
{
val = 0;
neighbors = vector<Node *>();
}
Node(int _val)
{
val = _val;
neighbors = vector<Node *>();
}
Node(int _val, vector<Node *> _neighbors)
{
val = _val;
neighbors = _neighbors;
}
};
```
### after
```cpp
```
## 答案
```cpp
class Solution
{
public:
unordered_map<Node *, Node *> ump;
Node *cloneGraph(Node *node)
{
if (node == nullptr)
return node;
if (ump.find(node) == ump.end())
return ump[node];
Node *new_node = new Node(node->val);
ump[node] = new_node;
for (auto &n : node->neighbors)
{
new_node->neighbors.emplace_back(cloneGraph(n));
}
return new_node;
}
};
```
## 选项
### A
```cpp
class Solution
{
public:
Node *cloneGraph(Node *node)
{
if (node == NULL)
return nullptr;
queue<Node *> q;
map<Node *, Node *> visit;
q.push(node);
Node *newNode;
while (!q.empty())
{
Node *now = q.front();
q.pop();
newNode = new Node(now->val);
visit[now] = newNode;
for (auto x : now->neighbors)
{
if (!visit.count(x))
{
q.push(x);
}
}
}
int i = 0;
for (auto x : visit)
{
Node *now = x.first;
for (auto y : now->neighbors)
{
x.second->neighbors.push_back(visit[y]);
}
}
return visit.find(node)->second;
}
};
```
### B
```cpp
class Solution
{
public:
map<int, Node *> list;
Node *cloneGraph(Node *node)
{
if (node == NULL)
return NULL;
Node *new_node = new Node(node->val, vector<Node *>(node->neighbors.size(), NULL));
list.insert(map<int, Node *>::value_type(new_node->val, new_node));
for (int i = 0; i < new_node->neighbors.size(); i++)
{
if (list.count(node->neighbors[i]->val) > 0)
new_node->neighbors[i] = list[node->neighbors[i]->val];
else
new_node->neighbors[i] = cloneGraph(node->neighbors[i]);
}
return new_node;
}
};
```
### C
```cpp
class Solution
{
public:
Node *cloneGraph(Node *node)
{
unordered_map<Node *, Node *> m;
return helper(node, m);
}
Node *helper(Node *node, unordered_map<Node *, Node *> &m)
{
if (!node)
return NULL;
if (m.count(node))
return m[node];
Node *clone = new Node(node->val);
m[node] = clone;
for (Node *neighbor : node->neighbors)
{
clone->neighbors.push_back(helper(neighbor, m));
}
return clone;
}
};
```
{
"node_id": "569d5e11c4fc5de7844053d9a733c5e8",
"keywords": [
"leetcode",
"课程表 II"
],
"children": [],
"export": [
"solution.json"
],
"title": "课程表 II"
}
\ No newline at end of file
<p>现在你总共有 <code>numCourses</code> 门课需要选,记为&nbsp;<code>0</code>&nbsp;&nbsp;<code>numCourses - 1</code>。给你一个数组&nbsp;<code>prerequisites</code> ,其中 <code>prerequisites[i] = [a<sub>i</sub>, b<sub>i</sub>]</code> ,表示在选修课程 <code>a<sub>i</sub></code><strong>必须</strong> 先选修&nbsp;<code>b<sub>i</sub></code></p>
<ul>
<li>例如,想要学习课程 <code>0</code> ,你需要先完成课程&nbsp;<code>1</code> ,我们用一个匹配来表示:<code>[0,1]</code></li>
</ul>
<p>返回你为了学完所有课程所安排的学习顺序。可能会有多个正确的顺序,你只要返回 <strong>任意一种</strong> 就可以了。如果不可能完成所有课程,返回 <strong>一个空数组</strong></p>
<p>&nbsp;</p>
<p><strong>示例 1:</strong></p>
<pre>
<strong>输入:</strong>numCourses = 2, prerequisites = [[1,0]]
<strong>输出:</strong>[0,1]
<strong>解释:</strong>总共有 2 门课程。要学习课程 1,你需要先完成课程 0。因此,正确的课程顺序为 <code>[0,1] 。</code>
</pre>
<p><strong>示例 2:</strong></p>
<pre>
<strong>输入:</strong>numCourses = 4, prerequisites = [[1,0],[2,0],[3,1],[3,2]]
<strong>输出:</strong>[0,2,1,3]
<strong>解释:</strong>总共有 4 门课程。要学习课程 3,你应该先完成课程 1 和课程 2。并且课程 1 和课程 2 都应该排在课程 0 之后。
因此,一个正确的课程顺序是&nbsp;<code>[0,1,2,3]</code> 。另一个正确的排序是&nbsp;<code>[0,2,1,3]</code></pre>
<p><strong>示例 3:</strong></p>
<pre>
<strong>输入:</strong>numCourses = 1, prerequisites = []
<strong>输出:</strong>[0]
</pre>
<p>&nbsp;</p>
<strong>提示:</strong>
<ul>
<li><code>1 &lt;= numCourses &lt;= 2000</code></li>
<li><code>0 &lt;= prerequisites.length &lt;= numCourses * (numCourses - 1)</code></li>
<li><code>prerequisites[i].length == 2</code></li>
<li><code>0 &lt;= a<sub>i</sub>, b<sub>i</sub> &lt; numCourses</code></li>
<li><code>a<sub>i</sub> != b<sub>i</sub></code></li>
<li>所有<code>[a<sub>i</sub>, b<sub>i</sub>]</code> 匹配 <strong>互不相同</strong></li>
</ul>
<p>&nbsp;</p>
<p><strong>拓展:</strong></p>
<ul>
<li>这个问题相当于查找一个循环是否存在于有向图中。如果存在循环,则不存在拓扑排序,因此不可能选取所有课程进行学习。</li>
<li><a href="https://www.coursera.org/specializations/algorithms" target="_blank">通过 DFS 进行拓扑排序</a> - 一个关于Coursera的精彩视频教程(21分钟),介绍拓扑排序的基本概念。</li>
<li>
<p>拓扑排序也可以通过&nbsp;<a href="https://baike.baidu.com/item/%E5%AE%BD%E5%BA%A6%E4%BC%98%E5%85%88%E6%90%9C%E7%B4%A2/5224802?fr=aladdin&amp;fromid=2148012&amp;fromtitle=%E5%B9%BF%E5%BA%A6%E4%BC%98%E5%85%88%E6%90%9C%E7%B4%A2" target="_blank">BFS</a>&nbsp;完成。</p>
</li>
</ul>
#include <bits/stdc++.h>
using namespace std;
class Solution
{
public:
vector<int> findOrder(int numCourses, vector<vector<int>> &prerequisites)
{
vector<int> result;
vector<int> fake;
vector<int> degree(numCourses, 0);
unordered_map<int, vector<int>> map;
for (vector<int> prerequisite : prerequisites)
{
map[prerequisite[1]].push_back(prerequisite[0]);
degree[prerequisite[0]]++;
}
queue<int> q;
for (int i = 0; i < numCourses; i++)
{
if (degree[i] == 0)
{
q.push(i);
}
}
while (!q.empty())
{
int cur = q.front();
result.push_back(cur);
q.pop();
for (int next : map[cur])
{
degree[next]--;
if (degree[next] == 0)
q.push(next);
}
}
return result.size() == numCourses ? result : fake;
}
};
\ No newline at end of file
{
"type": "code_options",
"author": "CSDN.net",
"source": "solution.md",
"exercise_id": "a9741627581943308853baf3c61cacae"
}
\ No newline at end of file
# 课程表 II
<p>现在你总共有 <code>numCourses</code> 门课需要选,记为&nbsp;<code>0</code>&nbsp;&nbsp;<code>numCourses - 1</code>。给你一个数组&nbsp;<code>prerequisites</code> ,其中 <code>prerequisites[i] = [a<sub>i</sub>, b<sub>i</sub>]</code> ,表示在选修课程 <code>a<sub>i</sub></code><strong>必须</strong> 先选修&nbsp;<code>b<sub>i</sub></code></p>
<ul>
<li>例如,想要学习课程 <code>0</code> ,你需要先完成课程&nbsp;<code>1</code> ,我们用一个匹配来表示:<code>[0,1]</code></li>
</ul>
<p>返回你为了学完所有课程所安排的学习顺序。可能会有多个正确的顺序,你只要返回 <strong>任意一种</strong> 就可以了。如果不可能完成所有课程,返回 <strong>一个空数组</strong></p>
<p>&nbsp;</p>
<p><strong>示例 1:</strong></p>
<pre>
<strong>输入:</strong>numCourses = 2, prerequisites = [[1,0]]
<strong>输出:</strong>[0,1]
<strong>解释:</strong>总共有 2 门课程。要学习课程 1,你需要先完成课程 0。因此,正确的课程顺序为 <code>[0,1] 。</code>
</pre>
<p><strong>示例 2:</strong></p>
<pre>
<strong>输入:</strong>numCourses = 4, prerequisites = [[1,0],[2,0],[3,1],[3,2]]
<strong>输出:</strong>[0,2,1,3]
<strong>解释:</strong>总共有 4 门课程。要学习课程 3,你应该先完成课程 1 和课程 2。并且课程 1 和课程 2 都应该排在课程 0 之后。
因此,一个正确的课程顺序是&nbsp;<code>[0,1,2,3]</code> 。另一个正确的排序是&nbsp;<code>[0,2,1,3]</code></pre>
<p><strong>示例 3:</strong></p>
<pre>
<strong>输入:</strong>numCourses = 1, prerequisites = []
<strong>输出:</strong>[0]
</pre>
<p>&nbsp;</p>
<strong>提示:</strong>
<ul>
<li><code>1 &lt;= numCourses &lt;= 2000</code></li>
<li><code>0 &lt;= prerequisites.length &lt;= numCourses * (numCourses - 1)</code></li>
<li><code>prerequisites[i].length == 2</code></li>
<li><code>0 &lt;= a<sub>i</sub>, b<sub>i</sub> &lt; numCourses</code></li>
<li><code>a<sub>i</sub> != b<sub>i</sub></code></li>
<li>所有<code>[a<sub>i</sub>, b<sub>i</sub>]</code> 匹配 <strong>互不相同</strong></li>
</ul>
<p>&nbsp;</p>
<p><strong>拓展:</strong></p>
<ul>
<li>这个问题相当于查找一个循环是否存在于有向图中。如果存在循环,则不存在拓扑排序,因此不可能选取所有课程进行学习。</li>
<li><a href="https://www.coursera.org/specializations/algorithms" target="_blank">通过 DFS 进行拓扑排序</a> - 一个关于Coursera的精彩视频教程(21分钟),介绍拓扑排序的基本概念。</li>
<li>
<p>拓扑排序也可以通过&nbsp;<a href="https://baike.baidu.com/item/%E5%AE%BD%E5%BA%A6%E4%BC%98%E5%85%88%E6%90%9C%E7%B4%A2/5224802?fr=aladdin&amp;fromid=2148012&amp;fromtitle=%E5%B9%BF%E5%BA%A6%E4%BC%98%E5%85%88%E6%90%9C%E7%B4%A2" target="_blank">BFS</a>&nbsp;完成。</p>
</li>
</ul>
<p>以下错误的选项是?</p>
## aop
### before
```cpp
#include <bits/stdc++.h>
using namespace std;
```
### after
```cpp
```
## 答案
```cpp
class Solution
{
public:
vector<int> findOrder(int numCourses, vector<pair<int, int>> &prerequisites)
{
vector<int> heads(numCourses, -1), degree(numCourses, 0), points, args;
pair<int, int> p;
vector<int> ans;
int from, to, count = 0, len = prerequisites.size();
for (int i = 0; i < len; ++i)
{
p = prerequisites[i];
from = p.second;
to = p.first;
args.push_back(heads[from]);
points.push_back(to);
heads[from] = count++;
}
queue<int> q;
for (int i = 0; i < numCourses; ++i)
if (degree[i] == 0)
{
q.push(i);
ans.push_back(i);
}
while (!q.empty())
{
from = q.front();
q.pop();
to = heads[from];
while (to != -1)
{
if (--degree[points[to]] == 0)
{
q.push(points[to]);
ans.push_back(points[to]);
}
to = args[to];
}
}
for (int i = 0; i < numCourses; ++i)
if (degree[i] > 0)
return vector<int>();
return ans;
}
};
```
## 选项
### A
```cpp
class Solution
{
public:
vector<int> findOrder(int numCourses, vector<vector<int>> &prerequisites)
{
int n = numCourses;
vector<unordered_set<int>> g(n);
vector<int> m(n);
for (auto &e : prerequisites)
{
int i = e[0], j = e[1];
g[j].insert(i), m[i]++;
}
queue<int> q;
auto f = [&](int i)
{
if (!m[i])
q.push(i);
};
for (int i = 0; i < n; i++)
f(i);
vector<int> res;
while (n--)
{
if (q.empty())
return {};
int i = q.front();
q.pop();
res.push_back(i);
for (int j : g[i])
m[j]--, f(j);
}
return res;
}
};
```
### B
```cpp
class Solution
{
private:
vector<vector<int>> edges;
vector<int> visited;
vector<int> result;
bool invalid;
public:
void dfs(int u)
{
visited[u] = 1;
for (int v : edges[u])
{
if (visited[v] == 0)
{
dfs(v);
if (invalid)
{
return;
}
}
else if (visited[v] == 1)
{
invalid = true;
return;
}
}
visited[u] = 2;
result.push_back(u);
}
vector<int> findOrder(int numCourses, vector<vector<int>> &prerequisites)
{
edges.resize(numCourses);
visited.resize(numCourses);
for (const auto &info : prerequisites)
{
edges[info[1]].push_back(info[0]);
}
for (int i = 0; i < numCourses && !invalid; ++i)
{
if (!visited[i])
{
dfs(i);
}
}
if (invalid)
{
return {};
}
reverse(result.begin(), result.end());
return result;
}
};
```
### C
```cpp
class Solution
{
public:
vector<int> findOrder(int numCourses, vector<vector<int>> &prerequisites)
{
vector<int> result;
vector<int> fake;
vector<int> degree(numCourses, 0);
unordered_map<int, vector<int>> map;
for (vector<int> prerequisite : prerequisites)
{
map[prerequisite[1]].push_back(prerequisite[0]);
degree[prerequisite[0]]++;
}
queue<int> q;
for (int i = 0; i < numCourses; i++)
{
if (degree[i] == 0)
{
q.push(i);
}
}
while (!q.empty())
{
int cur = q.front();
result.push_back(cur);
q.pop();
for (int next : map[cur])
{
degree[next]--;
if (degree[next] == 0)
q.push(next);
}
}
return result.size() == numCourses ? result : fake;
}
};
```
{
"node_id": "569d5e11c4fc5de7844053d9a733c5e8",
"keywords": [
"leetcode",
"矩阵中的最长递增路径"
],
"children": [],
"export": [
"solution.json"
],
"title": "矩阵中的最长递增路径"
}
\ No newline at end of file
<p>给定一个 <code>m x n</code> 整数矩阵 <code>matrix</code> ,找出其中 <strong>最长递增路径</strong> 的长度。</p>
<p>对于每个单元格,你可以往上,下,左,右四个方向移动。 你 <strong>不能</strong><strong>对角线</strong> 方向上移动或移动到 <strong>边界外</strong>(即不允许环绕)。</p>
<p> </p>
<p><strong>示例 1:</strong></p>
<img alt="" src="https://assets.leetcode.com/uploads/2021/01/05/grid1.jpg" style="width: 242px; height: 242px;" />
<pre>
<strong>输入:</strong>matrix = [[9,9,4],[6,6,8],[2,1,1]]
<strong>输出:</strong>4
<strong>解释:</strong>最长递增路径为 <code>[1, 2, 6, 9]</code></pre>
<p><strong>示例 2:</strong></p>
<img alt="" src="https://assets.leetcode.com/uploads/2021/01/27/tmp-grid.jpg" style="width: 253px; height: 253px;" />
<pre>
<strong>输入:</strong>matrix = [[3,4,5],[3,2,6],[2,2,1]]
<strong>输出:</strong>4
<strong>解释:</strong>最长递增路径是 <code>[3, 4, 5, 6]</code>。注意不允许在对角线方向上移动。
</pre>
<p><strong>示例 3:</strong></p>
<pre>
<strong>输入:</strong>matrix = [[1]]
<strong>输出:</strong>1
</pre>
<p> </p>
<p><strong>提示:</strong></p>
<ul>
<li><code>m == matrix.length</code></li>
<li><code>n == matrix[i].length</code></li>
<li><code>1 <= m, n <= 200</code></li>
<li><code>0 <= matrix[i][j] <= 2<sup>31</sup> - 1</code></li>
</ul>
class Solution
{
public:
static constexpr int dirs[4][2] = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}};
int m, n;
int longestIncreasingPath(vector<vector<int>> &matrix)
{
if (matrix.size() == 0 || matrix[0].size() == 0)
{
return 0;
}
m = matrix.size();
n = matrix[0].size();
int res = 0;
auto memo = vector<vector<int>>(m, vector<int>(n, 0));
for (int i = 0; i < m; ++i)
{
for (int j = 0; j < n; ++j)
{
if (memo[i][j])
res = max(res, memo[i][j]);
else
res = max(res, dfs(i, j, matrix, memo));
}
}
return res;
}
int dfs(int i, int j, vector<vector<int>> &matrix, vector<vector<int>> &memo)
{
int temp = 1;
for (int k = 0; k < 4; ++k)
{
int x = i + dirs[k][0];
int y = j + dirs[k][1];
if ((x >= 0) && (x < m) && (y >= 0) && (y < n) && (matrix[i][j] < matrix[x][y]))
{
if (memo[x][y])
temp = max(temp, memo[x][y] + 1);
else
temp = max(temp, dfs(x, y, matrix, memo) + 1);
}
}
memo[i][j] = temp;
return temp;
}
};
{
"type": "code_options",
"author": "CSDN.net",
"source": "solution.md",
"exercise_id": "7c564740d1b74108a046d92b0395a908"
}
\ No newline at end of file
{
"node_id": "569d5e11c4fc5de7844053d9a733c5e8",
"keywords": [
"leetcode",
"重新安排行程"
],
"children": [],
"export": [
"solution.json"
],
"title": "重新安排行程"
}
\ No newline at end of file
<p>给你一份航线列表 <code>tickets</code> ,其中 <code>tickets[i] = [from<sub>i</sub>, to<sub>i</sub>]</code> 表示飞机出发和降落的机场地点。请你对该行程进行重新规划排序。</p>
<p>所有这些机票都属于一个从 <code>JFK</code>(肯尼迪国际机场)出发的先生,所以该行程必须从 <code>JFK</code> 开始。如果存在多种有效的行程,请你按字典排序返回最小的行程组合。</p>
<ul>
<li>例如,行程 <code>["JFK", "LGA"]</code><code>["JFK", "LGB"]</code> 相比就更小,排序更靠前。</li>
</ul>
<p>假定所有机票至少存在一种合理的行程。且所有的机票 必须都用一次 且 只能用一次。</p>
<p> </p>
<p><strong>示例 1:</strong></p>
<img alt="" src="https://assets.leetcode.com/uploads/2021/03/14/itinerary1-graph.jpg" style="width: 382px; height: 222px;" />
<pre>
<strong>输入:</strong>tickets = [["MUC","LHR"],["JFK","MUC"],["SFO","SJC"],["LHR","SFO"]]
<strong>输出:</strong>["JFK","MUC","LHR","SFO","SJC"]
</pre>
<p><strong>示例 2:</strong></p>
<img alt="" src="https://assets.leetcode.com/uploads/2021/03/14/itinerary2-graph.jpg" style="width: 222px; height: 230px;" />
<pre>
<strong>输入:</strong>tickets = [["JFK","SFO"],["JFK","ATL"],["SFO","ATL"],["ATL","JFK"],["ATL","SFO"]]
<strong>输出:</strong>["JFK","ATL","JFK","SFO","ATL","SFO"]
<strong>解释:</strong>另一种有效的行程是 ["JFK","SFO","ATL","JFK","ATL","SFO"] ,但是它字典排序更大更靠后。
</pre>
<p> </p>
<p><strong>提示:</strong></p>
<ul>
<li><code>1 <= tickets.length <= 300</code></li>
<li><code>tickets[i].length == 2</code></li>
<li><code>from<sub>i</sub>.length == 3</code></li>
<li><code>to<sub>i</sub>.length == 3</code></li>
<li><code>from<sub>i</sub></code><code>to<sub>i</sub></code> 由大写英文字母组成</li>
<li><code>from<sub>i</sub> != to<sub>i</sub></code></li>
</ul>
{
"type": "code_options",
"author": "CSDN.net",
"source": "solution.md",
"exercise_id": "e46cb82d9614435b804fc3d7e3b1d305"
}
\ No newline at end of file
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册