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.
PROGRAM NAME: zerosum
INPUT FORMAT
A single line with the integer N (3 <= N <= 9).
SAMPLE INPUT (file zerosum.in)
7
OUTPUT FORMAT
In ASCII order, show each sequence that can create 0 sum with a +',
-‘, or ` ’ between each pair of numbers.
SAMPLE OUTPUT (file zerosum.out)
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
题意:1-N的数字,用+、-、空格来组合,按字典序输出最后结果为0的方法。空格表示将相邻的两个数连起来,比如说1-2 3,就是1-23。
DFS将每种情况走一次。step表示走到哪个数了,sum表示当前和,num表示当前DFS的数。
代码:
/*
ID:iam666
PROG:zerosum
LANG:C++
*/
#include <cstdio>
#include <algorithm>
#include <cstring>
#include <iostream>
#include <string>
using namespace std;
int n,m;
void dfs(int step,int sum,int num,string s)
{
string s1=s;
if(step==n)
{
if(num+sum==0)
{
cout<<s<<endl;
//return;
}
return ;
}
if(num>0)
{
//printf("%d %d %d\n",step,sum,num);
//cout<<s<<endl;
dfs(step+1,sum,num*10+step+1,s+" "+char(1+step+48));
}
else
dfs(step+1,sum,num*10-step-1,s+" "+char(1+step+48));
dfs(step+1,sum+num,step+1,s+"+"+char(step+1+48));
dfs(step+1,sum+num,-1*step-1,s+"-"+char(step+1+48));
}
int main (void)
{
// freopen("zerosum.in","r",stdin);
// freopen("zerosum.out","w",stdout);
cin>>n;
dfs(1,0,1,"1");
return 0;
}