题解 | #24点游戏算法#
24点游戏算法
http://www.nowcoder.com/practice/fbc417f314f745b1978fc751a54ac8cb
经典全排列变种体,在找全排列的时候可以在每个节点多dfs几次把运算的可能顺序的结果也得到,注意整数除法可能取0的情况
#include <iostream>
using namespace std;
const int N = 10;
int n = 4, g[N];
bool st[N], is24;
string s[N * N * N * N];
void dfs(int u, double res) {
if (u == n) {
if (res == 24) is24 = true;
}
for (int i = 1; i <= n; i ++) {
if (!st[i]) {
st[i] = true;
dfs(u + 1, res + g[i]);
dfs(u + 1, res - g[i]);
dfs(u + 1, res * g[i]);
dfs(u + 1, res / g[i]);
st[i] = false;
}
}
}
int main() {
for (int i = 1; i <= n; i ++) {
cin >> g[i];
}
dfs(0, 0);
if (is24) cout << "true" << endl;
else cout << "false" << endl;
}