题解 | #24点运算#
24点运算
http://www.nowcoder.com/practice/7e124483271e4c979a82eb2956544f9d
//递归(深度优先搜索)+map
#include<vector>
#include<unordered_map>
using namespace std;
vector<int> num2;
string temp;
vector<bool> signal(4);
bool begin1 = false;
void dfs(vector<int> tp,int n, int sum, string ans, vector<int> num){
if(n==4 && sum == 24){
begin1 = true;
temp = ans;
num2 = num;
return;
}
if(n == 4 || begin1) return;
for(int i =0 ; i < 4 ; i++ ){
if(!signal[i]){
signal[i] = true;
num.emplace_back(tp[i]);
dfs(tp, n + 1, sum + tp[i], ans + "+",num );
dfs(tp, n + 1, sum - tp[i], ans + "-",num );
dfs(tp, n + 1, sum * tp[i], ans + "*",num );
dfs(tp, n + 1, sum / tp[i], ans + "/",num );
signal[i] = false;
num.pop_back();
}
}
}
int main(){
vector<int> tp;
unordered_map<int, char> mp = {{1,'A'},{2,'2'},{3,'3'},{4,'4'},{5,'5'},{6,'6'},
{7,'7'},{8,'8'},{9,'9'},{10,'10'},{11,'J'},{12,'Q'},{13,'K'}};
string str;
while(cin >> str){
if(str == "JOKER" || str == "joker"){
cout << "ERROR" << endl;
return 0;
}else if(str == "10"){
tp.emplace_back(10);
}else if(str == "J"){
tp.emplace_back(11);
}else if(str == "Q"){
tp.emplace_back(12);
}else if(str == "K"){
tp.emplace_back(13);
}else if(str == "A"){
tp.emplace_back(1);
}else{
tp.emplace_back(str[0] - '0');
}
}
vector<int> num;
string ans;
for(int i =0 ; i < 4 ; i++ ){
signal[i] = true;
num.emplace_back(tp[i]);
dfs(tp, 1, tp[i], ans ,num);
signal[i] = false;
num.pop_back();
}
if(begin1) cout<<mp[num2[0]]<<temp[0]<<mp[num2[1]]<<temp[1]<<mp[num2[2]]<<temp[2]<<mp[num2[3]]<<endl;
else cout<<"NONE"<<endl;
return 0;
}