26041 Problem C 习题6-6 杨辉三角

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/a845717607/article/details/89213167

问题 C: 习题6-6 杨辉三角

时间限制: 1 Sec  内存限制: 12 MB

题目描述

按要求输入如下格式的杨辉三角

1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
1 5 10 10 5 1

最多输出10层

输入

输入只包含一个正整数n,表示将要输出的杨辉三角的层数。

输出

对应于该输入,请输出相应层数的杨辉三角,每一层的整数之间用一个空格隔开

样例输入

5

样例输出

1
1 1
1 2 1
1 3 3 1
1 4 6 4 1

经验总结

emmmm,稍微开始有点难度了,这一题,其实应该算是一个递推模拟,弄懂这个数字金字塔的计算规律,除了金字塔的边界数字都是1,中间的数字等于上一层的左右两个数之和,像这样:
                       1
                     1  1
                   1  2  1
                 1  3  3  1
               1  4  6  4  1
             1  5 10 10 5 1
看得就很清晰了,规律知道了,实现起来就很简单了~

AC代码

#include <cstdio>
int main()
{
	int count;
	const int n = 10;
	const int m = 2 * n-1;
	int arr[n + 1][m] = { 0 };
	for (int i = 0; i < n; i++)
	{
		arr[i][n - i- 1] = 1;
		arr[i][n + i -1] = 1;
	}
	for (int i = 2; i < n; i++)
		for (int j = n - i + 1; j < n-2+i; j = j + 2)
			arr[i][j] = arr[i - 1][j - 1] + arr[i - 1][j + 1];
	scanf("%d",&count);
	for(int i=0;i<count;i++)
	{
		for(int j=0;j<m;j++)
			if(arr[i][j]!=0)
				printf("%d ",arr[i][j]);
		printf("\n");
	}
	return 0;
}

猜你喜欢

转载自blog.csdn.net/a845717607/article/details/89213167