题解 | #24点游戏算法#
24点游戏算法
https://www.nowcoder.com/practice/fbc417f314f745b1978fc751a54ac8cb
#include <iostream> #include <vector> using namespace std; bool dfs(vector<int>& arr, vector<bool>& used, int k, double res){ if(k==4&&res==24) return true; if(k==4&&res!=24) return false; bool ret = false; for(int i=0;i<4;i++){ if(!used[i]){ int n = arr[i]; used[i] = true; ret|=dfs(arr, used, k+1, res+n); ret|=dfs(arr, used, k+1, res-n); ret|=dfs(arr, used, k+1, res*n); ret|=dfs(arr, used, k+1, res/n); used[i] = false; } } return ret; } int main() { vector<int> num(4); while (cin>>num[0]>>num[1]>>num[2]>>num[3]) { vector<bool> used(4, false); bool ret = dfs(num, used, 0, 0); cout<<(ret?"true":"false")<<endl; } }