【算法】二项式定理打印杨辉三角

题目:

输入一个数,不利用数组或动态空间,打印出这个数对应的杨辉三角,多组输入

思路:

通过二项式定理,杨辉三角第 n 行 m 列的数(n, m从0开始),对应 n 次二次项展开的第 m 个系数

即:arr[n][m] = n! / (m! * (n-m)!)

源码:

#include <iostream>
using namespace std;

int factorial(int n)
{
	int res = 1;
	for (int i = 1; i <= n; ++i)
	{
		res *= i;
	}
	return res;
}

int main()
{
	int n;
	while (cin >> n)
	{
		for (int i = 0; i < n; ++i)
		{
			for (int j = 0; j <= i; ++j)
			{
				cout << factorial(i) / (factorial(j) * factorial(i - j)) << " ";
			}
			cout << endl;
		}
		cout << endl;
	}
	return 0;
}

猜你喜欢

转载自blog.csdn.net/phoenixFlyzzz/article/details/130436596