# 2.3.3 Zero Sum 和为零

2.3.3 Zero Sum 和为零

``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 <stdio.h>

int n;
char str[20];

void dfs(int i,int t,int sum,char flag){
if(i==n){
sum+=t;
if(sum==0)
printf("%s\n",str);
return ;
}
if(flag==' '){
if(t<0)
t=t*10-i-1;
else
t=t*10+i+1;
}
else{
sum+=t;
t=i+1;
if(flag=='-')
t=-t;
}
str[2*i]=i+'1';
if(i==n-1){
str[2*i+1]=0;
dfs(i+1,t,sum,0);
return ;
}
str[2*i+1]=' ';
dfs(i+1,t,sum,' ');
str[2*i+1]='+';
dfs(i+1,t,sum,'+');
str[2*i+1]='-';
dfs(i+1,t,sum,'-');
}

int main(){
while(scanf("%d",&n)!=EOF){
dfs(0,0,0,'+');
}
return 0;
}``````

``````#include <stdio.h>

int n;
char str[20];

void dfs(int i,int t,int sum,char flag){
if(i==n){
sum+=t;
if(sum==0)
printf("%s\n",str);
return ;
}
if(flag==' '){
if(t<0)
t=t*10-i-1;
else
t=t*10+i+1;
}
else{
sum+=t;
t=i+1;
if(flag=='-')
t=-t;
}
str[2*i]=i+'1';
if(i==n-1){
str[2*i+1]=0;
dfs(i+1,t,sum,0);
return ;
}
str[2*i+1]=' ';
dfs(i+1,t,sum,' ');
str[2*i+1]='+';
dfs(i+1,t,sum,'+');
str[2*i+1]='-';
dfs(i+1,t,sum,'-');
}

int main(){
while(scanf("%d",&n)!=EOF){
dfs(0,0,0,'+');
}
return 0;
}``````