Zero Sum

来源:互联网 发布:mac开机显示问号文件夹 编辑:程序博客网 时间:2024/06/05 14:10

Zero Sum

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+71+2-3-4+5+6-71-2 3+4+5+6+71-2 3-4 5+6 71-2+3+4-5+6-71-2-3-4-5+6+7




题解 回溯法,回溯每一空的符号



#include<cstdlib>

#include<cstdio>
#include<iostream>
void tt(int,int,int,int);
void out();
int a[10];
int n;
int main()
{
freopen("zerosum.in","r",stdin);
freopen("zerosum.out","w",stdout);
scanf("%d",&n);
tt(2,0,1,1);
return 0;
}
void out()//输出
{
printf("%d",1);
for (int i=2;i<=n;i++) //
{
if (a[i]==2) printf("%c",'+');
if (a[i]==3) printf("%c",'-');
if (a[i]==1) printf("%c",' ');
printf("%d",i);
     }
    std::cout<<'\n';
    return;
}
void tt(int x,int k,int p,int f)
{
  if (x==n+1)//边界;
   {
if (k+p*f==0) out();
return;
   }
  for (int i=1;i<=3;i++)//枚举
  {
  a[x]=i;
  switch (i)
  {
case 1:tt(x+1,k,p*10+x,f);
break;
case 2:tt(x+1,k+p*f,x,1);
break;
case 3:tt(x+1,k+p*f,x,-1);
break;
  }
  }
}
0 0