题解 | #24点游戏算法#
24点游戏算法
https://www.nowcoder.com/practice/fbc417f314f745b1978fc751a54ac8cb
这题我是真的不会,完全是在b站学习大佬的解法, 用的是地柜的思路
#include<iostream> #include<vector> #include<algorithm> #include <cmath> using namespace std; bool result(vector<int> num) { int n = num.size(); if (n == 1) { if (num[0] == 24) { return true; } else { return false; } } // 每次选取两个任意值进行加减乘除运算, 然后放入到除去运算两个数的新数组中,在重复这一过程 for (int i = 0; i < n; i++) { for (int j = i + 1; j < n; j++) { int a = num[i]; int b = num[j]; vector<int> newNum; for (int k = 0; k < n; k++) { if (k != i && k != j) { newNum.push_back(num[k]); } } newNum.push_back(-1); newNum.back() = a + b; if (result(newNum)) return true; newNum.back() = a - b; if (result(newNum)) return true; newNum.back() = a * b; if (result(newNum)) return true; if (b != 0) { newNum.back() = a / b; if (result(newNum)) return true; } } } return false; } int main() { int data; vector<int> num; for (int i = 0; i < 4; i++) { cin >> data; num.push_back(data); } if (result(num)) cout << "true" << endl; else cout << "false" << endl; }