您的位置:首页 > 其它

等式变换

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;然后又回到之前的解法,递归
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: