hdu_problem_2032_杨辉三角

本文介绍了使用二维动态数组和组合数公式两种方法来实现杨辉三角的算法。通过对比,展示了不同算法的优缺点,如递归次数过多会导致超时等问题。适合初学者理解和实践算法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

用二维动态数组(AC)

/*
*
*Problem Description
*还记得中学时候学过的杨辉三角吗?具体的定义这里不再描述,你可以参考以下的图形:
*1
*1 1
*1 2 1
*1 3 3 1
*1 4 6 4 1
*1 5 10 10 5 1
*
*
*Input
*输入数据包含多个测试实例,每个测试实例的输入只包含一个正整数n(1<=n<=30),表示将要输出的杨辉三角的层数。
*
*
*Output
*对应于每一个输入,请输出相应层数的杨辉三角,每一层的整数之间用一个空格隔开,每一个杨辉三角后面加一个空行。
*
*
*Sample Input
*2 3
*
*
*Sample Output
*1
*1 1
*
*1
*1 1
*1 2 1
*
*
*Author
*lcy
*
*
*Source
*C语言程序设计练习(五)
*
*
*Recommend
*lcy
*
*/
#include<iostream>
using namespace std;
int main() {
 int n; // 层数
 int **a;
 while (cin >> n) {
  a = new int*[n];
  for (int i = 0; i < n; i++) {
   a[i] = new int[n];
   a[i][i] = 1;
   a[i][0] = 1;
  }
  for (int i = 0; i < n; i++) {
   for (int j = 1; j <= i - 1; j++) {
    a[i][j] = a[i-1][j-1] + a[i-1][j];
   }
  }
  for (int i = 0; i < n; i++) {
   for (int j = 0; j <= i; j++) {
    if (j != 0) cout << " ";
    cout << a[i][j];
   }
   cout << endl;
  }
  cout << endl;
  for (int i = 0; i < n; i++)
   delete[] a[i];
  delete[] a;
 }
 system("pause");
 return 0;
}

用组合数公式(没有AC,因为递归次数过多会超时)

#include<iostream>
using namespace std;
int zuhe(int n, int k) {
 if (n == k || k == 0) return 1;
 else return zuhe(n - 1, k) + zuhe(n - 1, k - 1);
}
int main() {
 int n; // 层数
 while (cin >> n) {
  if (n == 1) { cout << 1 << endl << endl; continue; }
  for (int i = 0; i <= n - 1; i++) {
   for (int j = 0; j <= i; j++) {
    if (j != 0)
     cout << " ";
    cout << zuhe(i, j);
   }
   cout << endl;
  }
  cout << endl;
 }
 system("pause");
 return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值