杨辉三角

2018-01-29  本文已影响0人  李哈哈_bing

杨辉三角

  public static void printArray(int[][] arr)
    {
        for(int i = 0; i < arr.length; i++)
        {
            for(int j=0; j<arr[i].length; j++)
            {
                System.out.print(arr[i][j]+"\t");
            }

            System.out.println();

        }
    }
    public static void main(String[] args) {
//        分析:看这种图像的规律
//        A:任何一行的第一列和最后一列都是1
//        B:从第三行开始,每一个数据是它上一行的前一列和它上一行的本列之和。
//        6
//        1
//        1  1
//        1  2  1
//        1  3  3  1
//        1  4  6  4  1
//        1  5 10 10  5  1
        Scanner scanner = new Scanner(System.in);
        System.out.println("请输入行数");
        int row = scanner.nextInt();

        int[][] array = new int[row][];

        //循环生成的每一行
        //        A:任何一行的第一列和最后一列都是1
//        B:从第三行开始,每一个数据是它上一行的前一列和它上一行的本列之和。
        for(int i = 0; i < array.length; i++)
        {
            array[i] = new int[i+1];//给二维数组里的第二个数组定长度
            array[i][0] = 1;//第一列设置成1
            array[i][i] = 1;//最后一列设置成1
            if(i > 1)//从第三行开始
            {
                for(int j = 1; j <= i-1; j++)
                {
                    array[i][j] = array[i-1][j]/*上一行的本列*/ + array[i-1][j-1]/*上一行的前一列*/;
                }
            }

        }

        printArray(array);
    }
}

上一篇 下一篇

猜你喜欢

热点阅读