Consider the sequence of digits from 1 through N (where N=9) in increasing order: 1 2 3 ... N.
Now insert either a `+' for addition or a `-' for subtraction or a ` ' [blank] to run the digits together between each pair of digits (not in front of the first digit). Calculate the result that of the expression and see if you get zero.
Write a program that will find all sequences of length N that produce a zero sum.
/* ID:shi13891 LANG:C++ PROG:zerosum */ #include <iostream> #include <cstdlib> #include <cstdio> #include <cstring> using namespace std; char a[1000]; int n; void DFS(int k,int sum,int num) { if(k==n) { if(sum+num==0) puts(a); return; } if(a[2*k-1]=' ') DFS(k+1,sum,num>0?num*10+k+1:num*10-k-1); if(a[2*k-1]='+') DFS(k+1,sum+num,k+1); if(a[2*k-1]='-') DFS(k+1,sum+num,-k-1); } int main() { freopen("zerosum.in", "r", stdin); freopen("zerosum.out", "w", stdout); while(cin>>n) { memset(a,0,sizeof(a)); for(int i=0;i<n;i++) { a[2*i]=i+'1'; } DFS(1,0,1); } fclose(stdin); fclose(stdout); return 0; }