Compare commits

...

2 Commits

Author SHA1 Message Date
0dbd38babe feat: 100_same_tree 2025-02-27 23:58:16 +08:00
70b16df4db feat: 39_combination_sum 2025-02-27 23:41:47 +08:00
2 changed files with 65 additions and 0 deletions

31
100_same_tree/main.cpp Normal file
View 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);
}
};

View 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;
}
};