暴力枚举
2016-04-18 12:08
281 查看
题目如下:
解法 1
1、用一个10维数组match记录 构建每个数字所需要的 火柴数。 比如match[0] = 6 : 表示构建0需要6根火柴。
2、用一个二维数组res 存储 某行 + 某列 需要的火柴数目。比如: res[0][1] = 14 : 表示 0 + 1 = 1 ;这个等式需要消耗14根火柴
3、定义一个结构体数组,结构体如下
在计算的过程中,每发现一对的火柴数符合要求,就记录下行号和列号,存储到数组中。
4、计算完之后,输出结构体数组。
解法 2
上述解法的空间复杂度过高,容易爆栈。不需要保存计算结果,当满足要求时立即输出即可。
解法 1
1、用一个10维数组match记录 构建每个数字所需要的 火柴数。 比如match[0] = 6 : 表示构建0需要6根火柴。
2、用一个二维数组res 存储 某行 + 某列 需要的火柴数目。比如: res[0][1] = 14 : 表示 0 + 1 = 1 ;这个等式需要消耗14根火柴
3、定义一个结构体数组,结构体如下
struct mat{ int row; //行号 int col; //列号 }
在计算的过程中,每发现一对的火柴数符合要求,就记录下行号和列号,存储到数组中。
4、计算完之后,输出结构体数组。
#include <iostream> #include <algorithm> #include <vector> using namespace std; struct mat { int row; //行号 int col; //列号 }; #define SUM 18 #define MAX 200 int main() { // 对应序号所需要的火柴数量 int match[MAX] = { 6, 2, 5, 5, 4, 5, 6, 3, 7, 6 }; for (int i = 10; i < MAX; i++) { int tmp = 0; int j = i; while (j) { tmp += match[j % 10]; j = j / 10; } match[i] = tmp; } int arr[MAX][MAX] = { 0 }; vector<mat> res; for (int i = 0; i < MAX; i++) { for (int j = 0; j < MAX; j++){ if (i + j > MAX) continue; arr[i][j] = match[i] + match[j] + match[i+j] + 4; if (arr[i][j] == SUM) { mat tmp = { i, j }; res.push_back(tmp); } } } for (auto it = res.begin(); it != res.end(); it++) { cout << it->row << " + " << it->col << " = " << SUM << endl; } return 0; }
解法 2
上述解法的空间复杂度过高,容易爆栈。不需要保存计算结果,当满足要求时立即输出即可。
#include <iostream> #include <algorithm> #include <vector> using namespace std; // 对应序号所需要的火柴数量 int match[10] = { 6, 2, 5, 5, 4, 5, 6, 3, 7, 6 }; int fun(int val) { int num = 0; // 当val == 0时 while (val/10 != 0) // 满足条件时,表示val此时至少是个2位数 { num += match[val % 10]; val /= 10; } num += match[val]; return num; } int main() { int matNum; cin >> matNum; int k; int sum = 0; for (int i = 0; i <= 11111; i++) { for (int j = 0; j <= 11111; j++) { k = i + j; if (fun(i) + fun(j) + fun(k) == matNum - 4) { printf(" %d + %d = %d \n", i, j, k); sum++; } } } cout << sum << endl; return 0; }
相关文章推荐
- Android学习笔记之RatingBar1>简介 RatingBar为评分条控件,默认效果为若干个绿色的星星,如果想将其换成其他自定义图片就要自定义它的style。 RatingBar是SeekBa
- objective c怎么修改类名
- 爱在心中【tarjan + 缩点】
- LeetCode 55. Jump Game
- linux ssh上传和下载
- Service Broker完成实例之间的会话详细解读
- 博客
- CocoaPods安装和使用教程
- python模块:re模块
- python模块:re模块
- PAM登录代码
- SSL协议详解
- simpleOS 1.0
- SQL语句oracle中如何插入Date类型的数据
- Get请求出现乱码的解决方案
- 各种view
- oracle 手工建库
- AngularJS入门教程之AngularJS指令
- python脚本监控redis制作zabbix模板
- CentOS6下ssh无法连接