题解 | #24点游戏算法#
24点游戏算法
https://www.nowcoder.com/practice/fbc417f314f745b1978fc751a54ac8cb
#include <any> #include <iostream> #include <type_traits> #include <vector> using namespace std; bool flag = false; void dfs(vector<int>& v, int sum, int idx) { if (idx == v.size() && sum == 24) { flag = true; } for(int i=idx;i<v.size();i++){ swap(v[i], v[idx]); int oldsum=sum; sum = oldsum + v[idx]; dfs(v, sum, idx+1); sum = oldsum - v[idx]; dfs(v, sum, idx+1); sum = oldsum * v[idx]; dfs(v, sum, idx+1); sum = oldsum / v[idx]; dfs(v, sum, idx+1); swap(v[i], v[idx]); } } int main() { vector<int> vv; int t; while (cin>>t) { vv.push_back(t); } for(int i=0;i<vv.size();i++){ swap(vv[i], vv[0]); dfs(vv, vv[0], 1); swap(vv[i], vv[0]); } cout<<(flag?"true":"false"); } // 64 位输出请用 printf("%lld")