java 杨辉三角

java 杨辉三角,请编写一个程序,按题目要求输出杨辉三角中第 n 行第 m 个数字。

    // 杨辉三角值递归计算
    public static long numYH(int x, int y) {
        if (y == 1 || y == x) {
            // 第一列和 x=y 的列都为1
            return 1;
        } else {
            // 中间部分的值递归计算
            return numYH(x - 1, y - 1) + numYH(x - 1, y);
        }
    }

    public static void main(String[] args) {
        System.out.println("输出杨辉三角中第 n 行第 m 个数字?");
        Scanner scanner = new Scanner(System.in);
        System.out.print("请输入杨辉三角行数: ");
        //杨辉三角行数
        int rowsYH = scanner.nextInt();
        System.out.print("请输入杨辉三角列数: ");
        //杨辉三角列数
        int colsYH = scanner.nextInt();
        scanner.nextLine();
        System.out.println("======================杨辉三角:start");

        System.out.println("杨辉三角第" + rowsYH + "行,第" + colsYH + "列的值是:" + numYH(rowsYH, colsYH));
        System.out.println("==============不信你看看下面:");

        for (int i = 1; i <= rowsYH; i++) {
            // 左边空格区,把直角三角形挤压成等腰三角形
            for (int j = 1; j <= rowsYH - i; j++) {
                //每列4位空格
                System.out.format("%4s", "");
            }
            // 数字区
            for (int j = 1; j <= i; j++) {
                //控制每列数值8位长度
                System.out.format("%8d", numYH(i, j));
            }
            System.out.println();
        }
        System.out.println("======================杨辉三角:end");
    }

结果:

输出杨辉三角中第 n 行第 m 个数字?
请输入杨辉三角行数: 7
请输入杨辉三角列数: 5
======================杨辉三角:start
杨辉三角第7行,第5列的值是:15
==============不信你看看下面:
                               1
                           1       1
                       1       2       1
                   1       3       3       1
               1       4       6       4       1
           1       5      10      10       5       1
       1       6      15      20      15       6       1
======================杨辉三角:end
原文地址:https://www.cnblogs.com/bors/p/yh.html