24點遊戲演算法(HJ67)
阿新 • • 發佈:2020-08-02
一:解題思路
這道題目可以擴充套件為:從0到n中,任意選出m個數字,然後任意通過加減乘除的組合,得到一個定值,求是否存在這樣的組合?
二:完整程式碼示例 (C++版和Java版)
C++程式碼:
#include <iostream> #include <vector> #include <algorithm> using namespace std; void check(vector<int>& nums, int start, double result, bool& isSuccess) { if (start == nums.size()) {if (abs(result - 24) < 1e-6) { isSuccess = true; return; } } else { for (int i = start; i < nums.size(); i++) { check(nums,start+1,result+nums[start],isSuccess); check(nums,start+1,result-nums[start],isSuccess); check(nums,start+1,result*nums[start],isSuccess); check(nums,start+1,result/nums[start],isSuccess); } } } int main() { vector<int> nums(4,0); while (cin >> nums[0] >> nums[1] >> nums[2] >> nums[3]) { sort(nums.begin(),nums.end()); boolisSuccess = false; do { check(nums,0,0,isSuccess); if (isSuccess) break; } while (next_permutation(nums.begin(),nums.end())); if (isSuccess) cout << "true" << endl; else cout << "false" << endl; } return 0; }