趣味算法-巧填运算符
2016-02-28 17:10
316 查看
给定一个整数数组,和一个单独的数字,在数组的每一个元素中间填加 "+"或"-" 使其运算结果等于单独的数字例如给定的数组为{7 2 4} ,数字为 9。运算结果为7-2+4=9
规则1:数组中元素的位置不能变化。
规则2:如果无法实现则输出 Invalid
举例:
Input:
1 2 3 4 10
1 2 3 4 5
Output:
1+2+3+4=10
Invalid
想法:使用穷举法,使用递归在每个位置尝试每个运算符,如果不成立,则需要返回尝试前的状态。
程序示例:(给的测试数字中,最后一个为单独的结果)
规则1:数组中元素的位置不能变化。
规则2:如果无法实现则输出 Invalid
举例:
Input:
1 2 3 4 10
1 2 3 4 5
Output:
1+2+3+4=10
Invalid
想法:使用穷举法,使用递归在每个位置尝试每个运算符,如果不成立,则需要返回尝试前的状态。
程序示例:(给的测试数字中,最后一个为单独的结果)
#include <iostream> using namespace std; void calc(int arr[], int length, int final) { static int index = 0; static int sum = arr[0]; static bool isfind = false, iscomplete = false; static char* operators = NULL; if (index == 0) { operators = new char[length]; memset(operators, '+', length); } if (isfind) return; if (index == length-1) { if (sum == final) { iscomplete = true; isfind = true; operators[length-1] = '='; for (int i = 0; i < length; i++) cout << arr[i] << operators[i]; //ok cout << final << endl; delete[] operators; operators = NULL; } else { if (index == 0) { delete[] operators; operators = NULL; cout<<"Invalid" << endl; } } return; } if (!isfind) { index++; sum += arr[index]; operators[index] = '+'; calc(arr, length, final); if ((!isfind) && (!iscomplete)) { sum -= arr[index]; operators[index] = '+'; index--; } } if (!isfind) { index++; sum -= arr[index]; operators[index] = '-'; calc(arr, length, final); if ((!isfind) && (!iscomplete)) { sum += arr[index]; operators[index] = '+'; index--; } } if ((index == 0) && (!isfind)) { delete[] operators; operators = NULL; cout<<"Invalid" << endl; } } int main() { //int arr[2] = {3, 3}; //int arr[2] = {3, 4}; //int arr[3] = {2, 3, 4}; int arr[4] = {7, 2, 4, 9}; //int arr[5] = {1, 2, 3, 4, 10}; int length = sizeof(arr)/sizeof(arr[0]); calc(arr, length-1, arr[length-1]); cout<<endl; cin >> length; return 0; }
相关文章推荐
- Java引用和C++指针的区别
- No_16_0226 Java基础学习第七天
- 学习笔记1
- spring - ioc和aop
- BS一机双屏的解决方案
- 求一个字符串中的最大回文子串
- 为什么jdk中把String类设计成final?
- hdu 2005 第几天
- ZOJ1060
- Android绘图监听接口OnPreDrawListener详解
- java数组的增删改查
- 置换颜色的机关(Button和TextView的交互)
- 美丽世界游戏集合
- C++ 中的模板类声明头文件和实现文件分离后,如何能实现正常编译?
- 【Manthan, Codefest 16E】【DP 从右向左线性扫描不用ST-RMQ】Startup Funding 最大的min(取min,取max) + n值选k最小做权的期望
- HDOJ 2016 数据的交换输出
- 解决 web 字符编码乱码问题-----charSet 和PageEncoding的区别--request编码问题
- c++ 动态分配内存delete多次出现的错误
- 最小二乘法拟合非线性函数及其Matlab/Excel 实现(转)
- <<Differential Geometry of Curves and Surfaces>>笔记