华为的OJ平台上有两道24点的习题,一道是初级的,仅仅是从1-10中随机取4个数字(可以相同),计算能否通过加减乘除得到24点。另一道是中级的,通过给出4张纸牌计算能否得到24点。
目前采用的方法仅仅是暴力解,代码如下:
第一题的代码如下:
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
using namespace std;
void preDeal(vector<string> &res, string str)
{
for (int i = 0; i < (int)str.size(); ++i)
{
if (str[i] == '+' || str[i] == '*' || str[i] == '/' || str[i] == '(' || str[i] == ')')
res.push_back(str.substr(i, 1));
else if (str[i] == '-') {
if (i == 0 || (!isalnum(str[i - 1]) && str[i - 1] != ')')) //&&str[i - 1] != ']'&&str[i - 1] != '}'
{
int j = 1;
i++;
while (i + j <(int)str.size() && isalnum(str[i + j])) ++j;
string s = "-" + str.substr(i, j);
res.push_back(s);
i += j - 1;
}
else
res.push_back("-");
}
else if (str[i] == '[' || str[i] == '{')
res.push_back("(");
else if (str[i] == ']' || str[i] == '}')
res.push_back(")");
else {
int j = 1;
while (i + j <(int)str.size() && isalnum(str[i + j])) ++j;
res.push_back(str.substr(i, j));
i += j - 1;
}
}
}
int calculate(int b, int a, string s,bool &can)
{
if (s == "+")
return a + b;
else if (s == "-")
return a - b;
else if (s == "*")
return a*b;
else
{
if (a%b == 0)
{
return a / b;
}
can = false;
return -10000;
}
}
int getAnswer(vector<string> res,bool &can)
{
if (res.empty())
return 0;
vector<string> op;
vector<int> val;
for (int i = 0; i < (int)res.size(); i++)
{
if (res[i] == "+" || res[i]