杨辉三角

我的未来我决定 提交于 2019-12-05 06:39:08

杨辉三角

1. 递归方法

package sort;/** * @author WangXiaoeZhe * @Date: Created in 2019/11/22 13:04 * @description: */public class YangHuiF {    public static int fun(int i, int j) {        if (j == 1 || i == j) {            return 1;        } else {            return fun(i - 1, j) + fun(i - 1, j - 1);        }    }    public static void main(String[] args) {        /**         * 打印的行数         */        int length = 6;        for (int i = 1; i <= length; i++) {            /**             * 打印空格             */            for (int j = 1; j <= length - i; j++) {                System.out.print("  ");            }            for (int j = 1; j <= i; j++) {                System.out.printf("%4d", fun(i, j));            }            System.out.println();        }    }}

2.非递归方法

package sort;/** * @author WangXiaoeZhe * @Date: Created in 2019/11/22 13:22 * @description: */public class YangHui {    /**     * 非递归的方法     *     * @param args     */    public static void main(String[] args) {        int length = 6;        int[][] arr = new int[length][];        for (int i = 0; i < arr.length; i++) {            arr[i] = new int[i + 1];            for (int j = 0; j < arr.length - i - 1; j++) {                System.out.print("  ");            }            for (int j = 0; j < arr[i].length; j++) {                if (j == 0 || arr[i].length - 1 == j) {                    arr[i][j] = 1;                } else {                    arr[i][j] = arr[i - 1][j] + arr[i - 1][j - 1];                }                System.out.printf("%4d", arr[i][j]);            }            System.out.println();        }    }}
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!