设为首页 加入收藏

TOP

算法之旅――杨辉三角
2014-11-23 22:25:46 来源: 作者: 【 】 浏览:2
Tags:算法 之旅 杨辉 三角

杨辉三角又称为贾宪三角形,是二项式系数在三角形中的一种几何排列。

  杨辉三角形拥有以下几点性质:

每行数字左右对称,从1开始,从左到右依次增大,然后依次减小,最后回到1。
n行中的数字个数为n个。
第n行数字和为2^(n-1)。
每个数字等于上一行的左右两个数字之和。可用此性质写出整个帕斯卡三角形。
将第2n+1行第1个数,跟第2n+2行第3个数、第2n+3行第5个数……连成一线,这些数的和是第2n个斐波那契数。
将第2n行第2个数,跟第2n+1行第4个数、第2n+2行第6个数……这些数之和是第2n-1个斐波那契数。
第n行的第1个数为1,第二个数为1×(n-1),第三个数为1×(n-1)×(n-2)/2,第四个数为1×(n-1)×(n-2)/2×(n-3)/3…依此类推。
两个未知数和的n次方运算后的各项系数依次为杨辉三角的第n行。
  以下为打印一个杨辉三角形的简单算法:

1 import java.util.Scanner;

2 public class YanghuiTriangle {

3 public static void main(String[] args) {

4 int num;

5 num = 0;

6 System.out.println("please input yanghui Triangle number 1of plies:");

7 Scanner input = new Scanner(System.in);

8 num = input.nextInt();

9 if(num < 0)

10 System.out.println("what you input is not non");

11 else {

12 System.out.print("yanghui triangle is:");

13 }

14 if(num !=0)

15 {

16 int[][] data = new int [num][num];

17 for (int i =0; i < data.length; i++) {

18 for(int j = 0 ; j <=i ; j++) {

19 if((j==0)||(j==i)) {

20 data[i][j]=1;

21 }

22 else if(i>=2&&j>=1) {

23 data[i][j]=data[i-1][j] + data[i-1][j-1]

;24 }

25 }

26 }

27 for(int l=0;l

28 System.out.println();

29 for(int m=0;m

30 if(data[l][m] !=0) {

31 System.out.print(data[l][m]+" ");

32 }

33 else {

34 System.out.print("");

35 }

36 }

37

38 }

39

40 }

41 }

42 }   

只要心中拥有梦想,我们就应为之奋斗。

】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
分享到: 
上一篇POJ 1719最大匹配 下一篇你可能不知道的switch

评论

帐  号: 密码: (新用户注册)
验 证 码:
表  情:
内  容: