题目1073:杨辉三角形
时间限制:1 秒
内存限制:32 兆
特殊判题:否
提交:2603
解决:1124
-
题目描述:
-
输入n值,使用递归函数,求杨辉三角形中各个位置上的值。
-
输入:
-
一个大于等于2的整型数n
-
输出:
-
题目可能有多组不同的测试数据,对于每组输入数据,
按题目的要求输出相应输入n的杨辉三角形。
-
样例输入:
-
6
-
样例输出:
-
1 1 1 2 1 1 3 3 1 1 4 6 4 1 1 5 10 10 5 1
//杨辉三角形 //排列组合c (nk)=(n-k+1)/k *c(n k-1) #include<stdio.h> #include<stdlib.h> typedef struct _node { int data; struct _node *next; struct _node *pre; }node; int main(void) { int n; while(scanf("%d",&n)!=EOF) { int i; node *head=(node *)malloc(sizeof(node)); node *q=(node *)malloc(sizeof(node)); node *end=(node *)malloc(sizeof(node)); //初始121 head->next=q; head->pre=NULL; head->data=1; q->next=end; q->data=2; q->pre=head; end->next=NULL; end->pre=q; end->data=1; for(i=0;i<n-1;i++) { if(i==0) printf("1 1\n"); else if(i==1) printf("1 2 1\n"); //行遍历 else { //非第一行 node *tag = (node *)malloc(sizeof(node)); tag=head; while(tag->next!=NULL) { node *temp = (node *)malloc(sizeof(node)); temp->data=tag->next->data+tag->data; if(tag!=head) {//非头结点加完消去自己 temp->pre = tag->pre; tag->pre->next = temp; temp->next = tag->next; tag->next->pre=temp; tag=tag->next;// } else {//头结点加完不消自己 temp->next=tag->next; temp->pre=tag; tag->next->pre=temp; tag->next=temp; tag=tag->next->next;// } } //输出部分 node *t=(node *)malloc(sizeof(node)); t=head; for(int k=0;k<i+2;k++) { k<i+1?printf("%d ",t->data):printf("%d\n",t->data); t=t->next; } } } } return 0; } /************************************************************** Problem: 1073 User: ranchothu Language: C Result: Accepted Time:10 ms Memory:1044 kb ****************************************************************/