Compare commits
2 Commits
df308e2d6f
...
0dbd38babe
Author | SHA1 | Date | |
---|---|---|---|
0dbd38babe | |||
70b16df4db |
31
100_same_tree/main.cpp
Normal file
31
100_same_tree/main.cpp
Normal file
@ -0,0 +1,31 @@
|
||||
#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 isSameTree(TreeNode* p, TreeNode* q) {
|
||||
function<bool(TreeNode*, TreeNode*)> dfs = [&](TreeNode* p, TreeNode* q) -> bool {
|
||||
// both p and q are null
|
||||
if (!p && !q) return true;
|
||||
|
||||
// one of p and q is null
|
||||
if (!p || !q) return false;
|
||||
|
||||
// the value of p and q are different
|
||||
if (p->val != q->val) return false;
|
||||
|
||||
return dfs(p->left, q->left) && dfs(p->right, q->right);
|
||||
};
|
||||
|
||||
return dfs(p, q);
|
||||
}
|
||||
};
|
34
39_combination_sum/main.cpp
Normal file
34
39_combination_sum/main.cpp
Normal file
@ -0,0 +1,34 @@
|
||||
#include <bits/stdc++.h>
|
||||
using namespace std;
|
||||
|
||||
class Solution {
|
||||
public:
|
||||
vector<vector<int>> combinationSum(vector<int>& candidates, int target) {
|
||||
sort(candidates.begin(), candidates.end());
|
||||
|
||||
vector<vector<int>> result;
|
||||
|
||||
function<void(int, vector<int>)> recursive = [&](int target, vector<int> chosen) {
|
||||
if (target < 0) return;
|
||||
|
||||
if (target == 0) {
|
||||
result.emplace_back(chosen);
|
||||
return;
|
||||
}
|
||||
|
||||
for (auto x : candidates) {
|
||||
if (chosen.size() > 0 && x > chosen.back()) {
|
||||
return;
|
||||
}
|
||||
|
||||
chosen.emplace_back(x);
|
||||
recursive(target - x, chosen);
|
||||
chosen.pop_back();
|
||||
}
|
||||
};
|
||||
|
||||
recursive(target, {});
|
||||
|
||||
return result;
|
||||
}
|
||||
};
|
Loading…
x
Reference in New Issue
Block a user