24点递归算法
View Code
1 #include <iostream> 2 #include <string> 3 #include <math.h> 4 using namespace std; 5 const double Threshold = 1e-6; 6 const int CardsNumber = 4; 7 const int ResultValue = 24; 8 double number[CardsNumber]; 9 string result[CardsNumber]; 10 bool PointGame(int n) 11 { 12 if(n == 1) 13 { 14 if(fabs(number[0] - ResultValue) < Threshold) 15 { 16 cout << result[0] << endl; 17 return true; 18 } 19 else 20 { 21 return false; 22 } 23 } 24 25 for(int i = 0; i < n; i++) 26 { 27 for(int j = i +1 ; j < n; j++) 28 { 29 double a, b; 30 string expa, expb; 31 a = number[i]; 32 b = number[j]; 33 number[j] = number[n - 1]; 34 35 expa = result[i]; 36 expb = result[j]; 37 result[j] = result[n-1]; 38 number[i] = a + b; 39 result[i] = '(' + expa + '+' + expb + ')'; 40 if(PointGame(n-1)) 41 { 42 return true; 43 } 44 number[i] = a - b; 45 result[i] = '(' + expa + '-' + expb + ')'; 46 if(PointGame(n-1)) 47 { 48 return true; 49 } 50 number[i] = b - a; 51 result[i] = '(' + expb + '-' + expa + ')'; 52 if(PointGame(n-1)) 53 { 54 return true; 55 } 56 number[i] = a * b; 57 result[i] = '(' + expa + '*' + expb + ')'; 58 if(PointGame(n-1)) 59 { 60 return true; 61 } 62 if(b != 0) 63 { 64 number[i] = a / b; 65 result[i] = '(' + expa + '/' + expb + ')'; 66 if(PointGame(n-1)) 67 { 68 return true; 69 } 70 } 71 72 if(a != 0) 73 { 74 number[i] = b / a; 75 result[i] = '(' + expb + '/' + expa + ')'; 76 if(PointGame(n-1)) 77 { 78 return true; 79 } 80 } 81 82 number[i] = a; 83 number[j] = b; 84 result[i] = expa; 85 result[j] = expb; 86 87 } 88 } 89 return false; 90 91 } 92 93 void main() 94 { 95 int x; 96 for(int i =0; i< CardsNumber; i++) 97 { 98 cout << "the " << i << "the number: "; 99 cin >> x; 100 number[i] = x; 101 result[i] = (char)(x + '0'); 102 } 103 104 if(PointGame(CardsNumber)) 105 { 106 cout << "Success" << endl; 107 108 } 109 else 110 { 111 cout << "failure" << endl; 112 } 113 114 115 }