杨辉三角算法

来源:互联网 发布:seo云优化heikw 编辑:程序博客网 时间:2024/04/27 21:11
杨辉三角的结构如下:
                         1
                     1     1
                 1      2      1
             1      3       3      1
         1      4       6      4      1
     1      5      10      10     5      1 
                   ......
 
算法如下:
#include<iostream.h>
#define MAX 100
void main()
{
       int a[MAX][MAX],i,j,n;
        cout<<"Enter n=";
       cin>>n;
       for(i=0;i<n;i++)
       {
              a[i][0]=1;//将边界上的点
               a[i][i]=1;//赋值为1
       }
       for(i=1;i<n;i++)
              for(j=1;j<i;j++)
                     a[i][j]=a[i-1][j-1]+a[i-1][j];//自己画个数组出来直观些
       for(i=0;i<n;i++)
       {
              for(j=0;j<=i;j++)
                     cout<<a[i][j]<<' ';
              cout<<endl;
       }
}

#include <iostream.h>
#include <iomanip.h>

typedef long (*FunPtr)( long, long );

long Factorial( long value );
long GetElementMethod1( long row, long col );
long GetElementMethod2( long row, long col );
void Output( long step, FunPtr funptr );

// 程序入口点
int main()
{
    FunPtr funptr;
   
    // 使用数学公式方法输出杨辉三角
    funptr = GetElementMethod1;
    Output( 6, funptr );

    cout << endl;

    // 使用递归输出杨辉三角
    funptr = GetElementMethod2;
    Output( 6, funptr );

    return 0;
}

// 获取当前参数的阶乘值
long Factorial( long value )
{
    if ( value == 0 || value == 1 )
        return 1;
    else
        return value * Factorial( value - 1 );
}

// 获取杨辉三角第row行第col列元素的值
long GetElementMethod1( long row, long col )
{
    return Factorial( row ) / ( Factorial( row - col ) * Factorial( col ) );
}

// 获取杨辉三角第row行第col列元素的值
long GetElementMethod2( long row, long col )
{
    if ( col == 0 || row == col )
        return 1;
    else
        return GetElementMethod2( row - 1, col - 1 ) + GetElementMethod2( row - 1, col );
}

// 输出杨辉三角,step为杨辉三角的阶数。
void Output( long step, FunPtr funptr )
{
    for ( int row = 0; row <= step; ++row )
    {
        for ( int col = 0; col <= row; col++ )
        {
            cout << setw( 5 ) << funptr( row, col );
        }

        cout << endl;
    }
}