8.29 贪心|摩尔投票
lc表达式树
class Solution {
private:
const double eps = 1e-5;
// 定义四种运算的函数对象
vector<function<double(double, double)>> ops = {
[](double a, double b) { return a + b; }, // 加法
[](double a, double b) { return a - b; }, // 减法
[](double a, double b) { return a * b; }, // 乘法
[this](double a, double b) { // 除法(处理除数为0)
if (fabs(b) < eps) return 1e18;
return a / b;
}
};
// 检查是否存在接近24的结果
bool check(const vector<double>& res) {
for (double num : res) {
if (fabs(num - 24) < eps) {
return true;
}
}
return false;
}
public:
bool judgePoint24(vector<int>& nums) {
// 生成4个数字的所有排列
sort(nums.begin(), nums.end());
do {
double a = nums[0], b = nums[1], c = nums[2], d = nums[3];
// 遍历所有运算组合(3次运算,每次4种选择)
for (int i = 0; i < 4; ++i) {
for (int j = 0; j < 4; ++j) {
for (int k = 0; k < 4; ++k) {
// 计算5种不同的运算顺序(表达式树结构)
double x1 = ops[i](ops[j](ops[k](a, b), c), d);
double x2 = ops[i](ops[j](a, ops[k](b, c)), d);
double x3 = ops[i](ops[j](a, b), ops[k](c, d));
double x4 = ops[i](a, ops[j](ops[k](b, c), d));
double x5 = ops[i](a, ops[j](b, ops[k](c, d)));
if (check({x1, x2, x3, x4, x5})) {
return true;
}
}
}
}
} while (next_permutation(nums.begin(), nums.end()));
return false;
}
};
lc229.原地hash,摩尔投票
lc881
sort+双指针+贪心
体重高的自觉点,先上船|・`)
class Solution
{
public:
int numRescueBoats(vector<int>& people, int limit) {
sort(people.begin(), people.end());
int left = 0, right = people.size() - 1;
int boats = 0;
while (left <= right)
{
if (people[left] + people[right] <= limit)
{
// 两人同乘一艘船
left++;
}
// 较重者单独乘一艘船
right--;
boats++;
}
return boats;
}
};
lc921
看个标题和样例 就可以写代码啦^^
class Solution {
public:
int minAddToMakeValid(string s)
{
stack<int> st;
for(auto& c:s)
{
if(!st.empty() && c==')' && st.top()!=c)
st.pop();
else
st.push(c);
}
return (int)st.size();
}
};