24点算法
来源:互联网 发布:java gui编程 对话框 编辑:程序博客网 时间:2024/06/08 13:17
题目描述:
1-9 9个数字中随机选出4个,使用+、-、*、/4种运算符,使它们的结果为24。
主要思想:穷举法
从1-9中选4个数共有9*8*7*6/4! = 126种选法,然后从126种选法中选出使用+、-、*、/4种运算符
结果为24的数字输出。代码如下:
#include<iostream>using namespace std;const int N = 4;void tweFourColck(int a[]);//穷举24点float calc(float a, float b, char oper);//计算void combination(int a[], int n, int k);//组合int main(){int a[N];combination(a, 9, N);system("pause");return 0;}float calc(float a, float b, char oper){switch (oper){case '+':return a + b;case '-':return a - b;case '*':return a * b;case '/':return a / b;}}void combination(int a[], int n, int k){if (k == 0){tweFourColck(a);return;}for (int i = n; i >= k; i--){a[k - 1] = i;combination(a, i - 1, k - 1);}}void tweFourColck(int a[]){char oper[] = { '+', '-', '*', '/' };for(int i = 0; i < 4; i++)for (int j = 0; j < 4; j++)for (int k = 0; k < 4; k++){float s = calc(a[0], a[1], oper[i]);s = calc(s, a[2], oper[j]);s = calc(s, a[3], oper[k]);if (s == 24){cout << a[0] << oper[i] << a[1] << oper[j];cout << a[2] << oper[k] << a[3] << endl;}}}
阅读全文
0 0
- [修改]24点算法
- 24点算法
- 24点算法
- 24点算法
- 24点算法
- 24点算法
- 24点经典算法
- 24点算法实现
- 24点算法2
- 24点算法。c++。
- 24点算法
- 24点游戏算法
- 24点算法
- 24点算法
- 24点游戏算法
- 24点算法
- 24点算法
- 24点问题算法
- vs2017常用快捷键
- Hadoop伪分布式搭建
- .gitignore文件失效问题处理
- 让自己写的程序也有api
- 现代操作系统之输入输出(三)
- 24点算法
- 持续集成之最佳实践
- Java基础(一):Java面向对象、面向对象封装、抽象类、接口、static、final
- Mac下的SVN客户端
- left join 和left outer join
- bzoj 3682: Phorni 后缀平衡树+线段树
- idea快捷键
- 汇编写启动代码之关看门狗
- [读书笔记]从零开始学C++程序设计