题意:该题也是通过经典的24点改编的,就是给你几个数要通过 + - * / 这几个运算后(中间可以加括号),可不可以得出结果24
24点在编程之美上也有介绍,应该是出自微软面试题
该题的思路就是通过深搜枚举各种可能性:
附代码:
#include <stdio.h> #include <math.h> #include <iostream> #include <string> #include <algorithm> #define Max_len 4 #define NUM 1e-6 int num; double record[Max_len]; int getNum(int n); using namespace std; int main(){ int N, i, k, m; scanf("%d", &N); while(N--){ scanf("%d %d", &m, &num); for(i = 0; i < m; i++){ scanf("%lf", &record[i]); } k = getNum(m); if(k) printf("Yes\n"); else{ printf("No\n"); } } return 0; } int getNum(int n){ int i, j; double a, b; // printf("%d\n", n); if(n == 1){ if(fabs(record[0] - num) < NUM){ return 1; } //printf("%lf", record[0]); // getchar(); return 0; } for(i = 0; i < n; i++){ for(j = i + 1; j < n; j++){ a = record[i]; b = record[j]; record[j] = record[n - 1]; record[i] = a + b; if(getNum(n - 1)) return 1; record[i] = a - b; if(getNum(n - 1)) return 1; record[i] = a * b; if(getNum(n - 1)) return 1; record[i] = b - a; if(getNum(n - 1)) return 1; if(b != 0){ record[i] = a / b; if(getNum(n - 1)) return 1; } if(a != 0){ record[i] = b / a; if(getNum(n - 1)) return 1; } record[i] = a; record[j] = b; } } return 0; }
原文:http://blog.csdn.net/huntinggo/article/details/19424407