Chinaunix首页 | 论坛 | 博客
  • 博客访问: 242811
  • 博文数量: 76
  • 博客积分: 1410
  • 博客等级: 上尉
  • 技术积分: 745
  • 用 户 组: 普通用户
  • 注册时间: 2009-10-28 16:04
文章分类

全部博文(76)

文章存档

2013年(2)

2010年(21)

2009年(53)

我的朋友

分类:

2009-11-26 10:05:36

巴斯卡(Pascal)三角形基本上就是在解 nCr ,因為三角形上的每一個數字各對應一個nCr,其中 n 為 row,而 r 為 column,如下:
    0C0
   1C0 1C1
  2C0 2C1 2C2
 3C0 3C1 3C2 3C3
4C0 4C1 4C2 4C3 4C4

對應的數據如下圖所示: 

PHP:

<?php
function abc($n)
{
    //计算 存入数组
    for($i=1;$i<=$n;$i++)
    {
        for($j=0;$j<$i;$j++)
        {
            if($j == 0)
            {
                $temp[$i][$j] = 1;
            }
            else
            {
                $temp[$i][$j] = $temp[$i-1][$j-1] + $temp[$i-1][$j];
            }
        }
    }
    
    //显示
    $space = ' ';
    $con_out = count($temp);
    for($i=0;$i<=$con_out;$i++)
    {
        $con_in = count($temp[$i]);
        for($j=0;$j<$con_in;$j++)
        {
            if($j == 0)
            {
                echo str_repeat($space,($n-$i));
            }
            echo $temp[$i][$j].$space;
        }
        echo '
'
;
    }
}

abc(13);
?>


Python:

def abc(n):
    //Python的初始化二维数组,真是头疼
    temp = [[0 for col in range(n)] for row in range(n)]
    for i in range(1, n):
        for j in range(0, i):
            if j==0:
                temp[i][j] = 1
            else:
                temp[i][j] = temp[i-1][j-1] + temp[i-1][j]
    for i in range(0, n):
        for j in range(0, i):
            print(temp[i][j], end=" ")
        print('\n');


C:

/*
  Name: 巴斯卡
  Copyright: 1.0
  Author: Mervin.G
  Date: 2009-11-26
  Description: 输出N行后的数字
*/


#include <stdio.h>
#include <conio.h>
#include <windows.h>

void sjx(int n)
{
    int i;
    int j;
    int temp[n][n];
    
    //初始化整个数组值为0
    for(i=0;i<n;i++)
    {
        for(j=0;j<n;j++)
        {
            temp[i][j] = 0;
        }
    }
    
    for(i=0;i<n;i++)
    {
        for(j=0;j<i;j++)
        {
            if(j == 0)
            {
                temp[i][j] = 1;
            }
            else
            {
                if(j > 0 && i > 0)
                {
                    temp[i][j] = temp[i-1][j-1] + temp[i-1][j];
                }
                else
                {
                    temp[i][j] = temp[i][j] + 0;
                }
            }
        }
    }
    for(i=0;i<n;i++)
    {
        for(j=0;j<i;j++)
        {
            printf("%d ",temp[i][j]);
        }
        printf("\n");
    }
}

main()
{
    int igetch;
    sjx(14);
    
    //监听用户键盘操作,直到ESC时退出
    while (true)
    {
        igetch = getch();
        if(igetch == 27)
        {
            exit(0);
        }
        else
        {
            printf("%d\n",igetch);
        }
    }
}


阅读(551) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~