题目描述:如图是由14个'+'和14个'-'组成的符号三角形。2个同号下面是‘+’,异号是‘-’。在一般情况下,符号三角形的第一行有n个符号。要求对于给定的n,计算有多少个不同的符号三角形,使其所含的‘+’和‘-’个数相同。
------题目出自 《计算机算法设计与分析 第3版》 王晓东
代码如下:
#include <stdio.h>
#include <conio.h>
#define MAX 100
//global variables
int count=0;//the number of '-'
int sum=0;//the number of the result
int p[MAX][MAX]={0}; //1 is '-' 0 is '+'
int n=0;
int half=0;//half=n*(n+1)/4
void back_triangle(int t);
int main()
{
printf("Please input n:");
scanf("%d",&n);
half=n*(n+1)/2;
if(half%2!=0)
{
printf("The number that you input is not meaningful for this problem!");
getch();
return 1;
}
half/=2;
back_triangle(1);
printf("The result is %d",sum);
getch();
}
void back_triangle(int t)
{
if(count>half || t*(t-1)/2-count>half)//because of this,the "count==half" is not necessary
return ;
if(t>n /*&& count==half*/) //the count==half is not necessary
{
sum++;
for(int temp=1;temp<=n;temp++)
{
for(int tp=1;tp<=n;tp++)
{
printf("%d ",p[temp][tp]);
}
printf("\n");
}
printf("\n");
}
else
{
int i;
for(i=0;i<2;i++)
{
p[1][t]=i;
count+=i;
int j;
for(j=2;j<=t;j++)
{
p[j][t-j+1]=(p[j-1][t-j+1]^p[j-1][t-j+2]);
count+=p[j][t-j+1];
}
back_triangle(t+1);
for(j=2;j<=t;j++)
count-=p[j][t-j+1];
count-=i;
}
}
}参考资料:《计算机算法设计与分析 第3版》 王晓东

这是一篇关于符号三角形问题的博客,详细介绍了如何使用回溯法来解决这个问题。根据题目描述,当符号三角形的第一行有n个符号时,需要计算所有符号个数相等的不同三角形的数量。文章来源于《计算机算法设计与分析 第3版》王晓东的著作,并附有相关代码实现。
784

被折叠的 条评论
为什么被折叠?



