等式变换
2016-07-11 16:12
323 查看
第三题:等式变换
输入一个正整数X,在下面的等式左边的数字之间添加+号或者-号,使得等式成立。
1 2 3 4 5 6 7 8 9 = X
比如:
12-34+5-67+89 = 5
1+23+4-5+6-7-8-9 = 5
请编写程序,统计满足输入整数的所有整数个数。
输入: 正整数,等式右边的数字
输出: 使该等式成立的个数
样例输入:5
样例输出:21
#include<iostream>
#include<vector>
#include<string>
#include<map>
#include<algorithm>
using namespace std;
int vec2num(int st,int en)
{
int n(0);
for (int i = st; i < en; i++)
n = 10 * n + i + 1;
return n;
}
void solve(int x,vector<int>op, vector<vector<int>>&re)
{
if (op.empty())
{
for (int i = 1; i < 9; i++)
{
vector<int>oper,oper1;
oper.push_back(i);
int n = vec2num(i, 9);
solve(x -n , oper, re);
oper1.push_back(-i);
solve(x + n, oper1, re);
}
}
else
{
if (x == vec2num(0, abs(op.back())))
re.push_back(op);
else
{
for (int i = 1; i<abs(op.back());i++)
{
vector<int>oper(op), oper1(op);
oper.push_back(i);
int n = vec2num(i, abs(op.back()));
solve(x - n, oper, re);
oper1.push_back(-i);
solve(x + n, oper1, re);
}
}
}
}
int main()
{
int x(0);
while (cin >> x)
{
vector<vector<int>>re;
vector<int>op;
solve(x, op, re);
cout << re.size() << endl;
}
return 0;
}
思路:递归方法解决。开始等式右边是x,每次从等式末尾截取几位数字组成一个操作数n,其前面的操作符取正负,然后将这个操作数n移到等式右边,这样就要在剩下的数添加操作符使其值等于x+/-n;然后又回到之前的解法,递归
输入一个正整数X,在下面的等式左边的数字之间添加+号或者-号,使得等式成立。
1 2 3 4 5 6 7 8 9 = X
比如:
12-34+5-67+89 = 5
1+23+4-5+6-7-8-9 = 5
请编写程序,统计满足输入整数的所有整数个数。
输入: 正整数,等式右边的数字
输出: 使该等式成立的个数
样例输入:5
样例输出:21
#include<iostream>
#include<vector>
#include<string>
#include<map>
#include<algorithm>
using namespace std;
int vec2num(int st,int en)
{
int n(0);
for (int i = st; i < en; i++)
n = 10 * n + i + 1;
return n;
}
void solve(int x,vector<int>op, vector<vector<int>>&re)
{
if (op.empty())
{
for (int i = 1; i < 9; i++)
{
vector<int>oper,oper1;
oper.push_back(i);
int n = vec2num(i, 9);
solve(x -n , oper, re);
oper1.push_back(-i);
solve(x + n, oper1, re);
}
}
else
{
if (x == vec2num(0, abs(op.back())))
re.push_back(op);
else
{
for (int i = 1; i<abs(op.back());i++)
{
vector<int>oper(op), oper1(op);
oper.push_back(i);
int n = vec2num(i, abs(op.back()));
solve(x - n, oper, re);
oper1.push_back(-i);
solve(x + n, oper1, re);
}
}
}
}
int main()
{
int x(0);
while (cin >> x)
{
vector<vector<int>>re;
vector<int>op;
solve(x, op, re);
cout << re.size() << endl;
}
return 0;
}
思路:递归方法解决。开始等式右边是x,每次从等式末尾截取几位数字组成一个操作数n,其前面的操作符取正负,然后将这个操作数n移到等式右边,这样就要在剩下的数添加操作符使其值等于x+/-n;然后又回到之前的解法,递归
相关文章推荐
- Ubuntu 安装google chrome 浏览器(版本50+)
- LightOJ 1341 唯一分解定理
- 使UILabel垂直考上对齐
- LeetCode 349. Intersection of Two Arrays
- SQL代码应用示例
- ElasticSearch 安装 和java api
- 利用Navicate把SQLServer转MYSQL的方法(连数据)
- c#实现Foreach枚举_IEnumerable和IEnumerator
- Flatten Nested List Iterator
- CentOS6桌面右键打开终端(open termial)增加
- 史上最全最强SpringMVC详细示例实战教程
- 【unity3d开发】unity接入unity Ads详细流程
- java8学习 -- lambda表达式
- 【Python学习笔记】调试
- java.lang.UnsatisfiedLinkError: D:\Tomcat\apache-tomcat-7.0.37\bin\tcnative-1.dll: Can't load AMD 64
- 练习35——分支和函数
- Android 隐藏状态栏
- 借助下一代云演进实现业务转型
- 【unix网络编程第三版】阅读笔记(四):TCP客户/服务器实例
- 【unix网络编程第三版】阅读笔记(四):TCP客户/服务器实例