趣味算法-巧填运算符
来源:互联网 发布:使用vmware安装linux 编辑:程序博客网 时间:2024/05/16 05:09
给定一个整数数组,和一个单独的数字,在数组的每一个元素中间填加 "+"或"-" 使其运算结果等于单独的数字例如给定的数组为{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
想法:使用穷举法,使用递归在每个位置尝试每个运算符,如果不成立,则需要返回尝试前的状态。
程序示例:(给的测试数字中,最后一个为单独的结果)
#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;}
0 0
- 趣味算法-巧填运算符
- 填加减运算符算法
- 趣味算式填符号
- 【程序5】填运算符
- 【程序5】填运算符
- 枚举法填运算符
- 蓝桥杯 填符号凑算式 趣味运算 DFS枚举 字符串处理
- 运算符优先级的趣味记忆法
- 趣味算法
- 用枚举法填运算符
- 填运算符(C语言)
- 穷举法:填运算符游戏
- PHP填坑——运算符
- [填坑]重载运算符自用总结
- 趣味算法之趣味素数
- 趣味算法之趣味分数
- 填符号凑算式 趣味算式
- 历届试题 趣味算式填符号
- 8. String to Integer (atoi)
- Powerful Calculator(上海交大上机考试)
- Giraph运行
- HDOJ 1033 Edge
- poj2151概率dp
- 趣味算法-巧填运算符
- Pandas分组统计函数:groupby、pivot_table及crosstab
- 为什么jdk中把String类设计成final?
- UICollectionView 简单实用
- 客户端TIME_WAIT的解决方法与思考
- 个人vimrc配置备份
- 开启CSND技术博客之路
- Oracle db 控制文件笔记
- java接口