Description
请考虑一个由1到N(N=3, 4, 5 ... 9)的数字组成的递增数列:1 2 3 ... N。
现在请在数列中插入“+”表示加,或者“-”表示减,抑或是“ ”表示空白,来将每一对数字组合在一起(请不在第一个数字前插入符号)。
计算该表达式的结果并注意你是否得到了和为零。
请你写一个程序找出所有产生和为零的长度为N的数列。
Input
单独的一行表示整数N (3 <= N <= 9)。
Output
按照ASCII码的顺序,输出所有在每对数字间插入“+”, “-”, 或 “ ”后能得到和为零的数列。(注意:就算两个数字之间没有插入符号也应该保留空格)
Sample Input
7
Sample Output
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
解题思路:先初始化,然后用深搜,当dep不等于n时继续往下搜,如果等于n的话就对目前结果进行处理,然后输出。
程序:
var
ph,num:array [0..9] of longint;
fh:array [1..3] of char;
n,tot:longint;
procedure init;
begin
fh[1]:=' ';
fh[2]:='+';
fh[3]:='-';
readln(n);
ph[n]:=2;
end;
procedure dfs(dep:longint);
var
i,ans:longint;
s,s1:string;
begin
if dep<>n then
begin
for i:=1 to 3 do
begin
ph[dep]:=i;
dfs(dep+1);
end;
end
else
begin
str(1,s);
tot:=0;
for i:=1 to n do
begin
case ph[i] of
1:begin
str(i+1,s1);
s:=s+s1;
end;
2:begin
inc(tot);
val(s,num[tot]);
str(i+1,s);
end;
3:begin
inc(tot);
val(s,num[tot]);
str(i+1,s);
s:='-'+s;
end;
end;
end;
ans:=0;
for i:=1 to tot do
inc(ans,num[i]);
if ans=0 then
begin
for i:=1 to n-1 do
write(i,fh[ph[i]]);
writeln(n);
end
else exit;
end;
end;
begin
init;
dfs(1);
end.