24點遊戲演算法 (無腦遞歸暴力破解)

  • 2019 年 11 月 8 日
  • 筆記

版權聲明:本文為部落客原創文章,遵循 CC 4.0 BY-SA 版權協議,轉載請附上原文出處鏈接和本聲明。

本文鏈接:https://blog.csdn.net/weixin_42449444/article/details/85318582

題目描述

問題描述:給出4個1-10的數字,通過加減乘除,得到數字為24就算勝利 輸入: 4個1-10的數字。[數字允許重複,但每個數字僅允許使用一次,測試用例保證無異常數字] 輸出: true or false

輸入描述:

輸入4個int整數

輸出描述:

返回能否得到24點,能輸出true,不能輸出false

輸入樣例:

7 2 1 10

輸出樣例:

true

解題思路:

利用vector來實現無腦遞歸暴力破解。需要注意的是用while來輸入多組測試用例。

AC程式碼:

#include <bits/stdc++.h>  using namespace std;    bool is24(vector<double> a,double result)  {      int sum = 24;      if(a.empty())      {          return result == sum;      }      for (int i = 0; i < a.size(); i++)      {          vector<double> b(a);          b.erase(b.begin()+i);          if(is24(b,result+a[i])||is24(b,result-a[i])||is24(b,result*a[i])||is24(b,result/a[i]))          {              return true;          }      }      return false;  }    int main()  {      vector<double> a(4);      while(cin >> a[0] >> a[1] >> a[2] >> a[3])      {          if(is24(a,0))          {              cout << "true" << endl;          }          else          {              cout << "false" << endl;          }      }      return 0;  }