给定一个由 1∼N 构成的序列:1,2,…,N。
现在,你要在序列的数字与数字之间插入一些符号,插入+表示加法运算,插入-表示减法运输,插入(空格)表示数字合并为一个数。
在全部插入完毕后,将得到一个可以看作表达式的新序列。
计算该表达式的结果,看看结果是否为 0。
现在,请你编写一个程序,给定整数 N,找到并输出所有的长度为 N 且总和为零的序列。
输入格式
共一行,包含一个整数 N。
输出格式
按照 ASCII 码的顺序输出所有满足条件的序列,每个序列占一行。
数据范围
3≤N≤9
输入样例:
7
输出样例:
1+2-3+4-5-6+7
1+2-3-4+5+6-7
1-2 3+4+5+6+7
1-2 3-4 5+6 7
1-2+3+4-5+6-7
1-2-3-4-5+6+7
#include <iostream>
#include <cstring>
#include <algorithm>
#include <sstream>
using namespace std;
int n;
string stringtoint(int x){
string res;
stringstream ss;
ss<<x;
ss>>res;
return res;
}
bool check(string num)
{
num = '+' + num;
int res = 0;
for (int i = 0; i < num.size(); i ++ )
{
int j = i + 1, x = 0;
while (j < num.size() && num[j] != '+' && num[j] != '-')
{
char c = num[j];
if (c != ' ') x = x * 10 + c - '0';//空格可以进来
j ++ ;
}
if (num[i] == '+') res += x;
else res -= x;
i = j - 1;
}
return res == 0;
}
void dfs(int u, string num)
{
if (u > n)
{
if (check(num)) cout << num << endl;
return;
}
char ops[] = {' ', '+', '-'};
for (int i=0;i<3;i++)
dfs(u + 1, num + ops[i] + stringtoint(u));
}
int main()
{
cin >> n;
dfs(2, "1");
return 0;
}
#include<cstdio>
#include<cstring>
using namespace std;
int n,a[11];//a[2]开始存放符号
char s[3]={' ','+','-'};
inline bool check()//判断是否可行,整个程序最难的地方
{
int ans=0,t;
for(int i=1;i<=n;i++)//n个符号
{
if(a[i]==0) continue;//如果是‘ ’就不用管了
t=i;
for(int j=i+1;j<=n;j++)//找‘ ’
{
if(a[j]!=0) break;//如果不是空格,就不管了
t=t*10+j;
}
if(a[i]==1) ans+=t;//加或减
else ans-=t;
}
return ans==0;
}
void dfs(int k)
{
if(k==n+1)//如果符号找完了
{
if(check()==true)//判断是否可以
{
printf("1");//如果可以就输出
for(int i=2;i<=n;i++) printf("%c%d",s[a[i]],i);
printf("\n");
}
return;
}
for(int i=0;i<=2;i++)//递归
{
a[k]=i;//记录值
dfs(k+1);//往下搜索
}
}
int main()
{
scanf("%d",&n);a[1]=1;//刚刚说的在1之前放符号
dfs(2);//从第二个开始
return 0;
}