杨辉三角算法的实现(java)

 

       杨辉三角形有数字排列,可以把它看做一个数字表,其基本特性是两侧数值均为1,其他位置的数值是其正上方与左上角数值之和。这里给出两种实现方法。

第一种:

       再创建的YanghuiTriabgle类中的主方法创建一个二维数组,并指定二维数字的第一维长度,这个数组同于存放杨慧三角形的数值表,通过双层for循环来实现第二维数组的长度,然后计算整个数组的每个元素的值。

关键代码如下:


public class YanghuiTriangle {
	public static void main(String[] args) {
		int number[][] = new int[10][];
        //遍历二维数组第一层
		for (int i = 0; i < number.length; i++) {
			number[i]=new int[i+1];             //初始化第二层数组的大小
			for (int j = 0; j <= i; j++) {
				if (i==0||j==0||j==i) {         //将两侧的数组元素赋值为1
					number[i][j]=1;					
				}else {                         //其他数值根据公式计算
					number[i][j]=number[i-1][j]+number[i-1][j-1];
				}
				System.out.print(number[i][j]+"\t");	//输出数组元素		
			}
			System.out.println();               //换行
			
		}
	}
}

第二种:

实现过程相同,用的语句有些差别。

杨辉三角算法的实现:

public class YangHui {  
    public static void main(String[] args) {
        int[][] Array = new int[10][];
        for (int i = 0; i < Array.length; i++) {
            Array[i]=new int[i+1];            //定义二维数组的列数
            for (int j = 0; j < Array[i].length; j++) {
                if (i<=1) {                //如果是数组的前两行
                    Array[i][j]=1;            //将其设置为1
                    continue;
                }else {
                    //如果是行首或者行尾
                    if (j==0 || j==Array[i].length-1) {
                        Array[i][j] = 1;              //则设置为1
                    }else {              //根据杨辉三角进行计算
                        Array[i][j]=Array[i-1][j-1]+Array[i-1][j];
                    }
                }
            }
        }
        for (int i = 0; i < Array.length; i++) {            //输出杨辉三角
            for (int j = 0; j < Array[i].length; j++) {
                System.out.print(Array[i][j]+"\t");       
            }    
            System.out.println();
        }
    }
}

运行结果如下:

《杨辉三角算法的实现(java)》

如果有什么不懂的地方可以在下方留言或者私信,我会一一解答。

    原文作者:杨辉三角问题
    原文地址: https://blog.csdn.net/zxdspaopao/article/details/82934592
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞