杨辉三角

杨辉三角是一个很有特点的三角形,它的左边和右边都是1,而且它的某一行的值等于上一行的y+y-1的值。如图:
在这里插入图片描述
所以我们可以用递归得出规律,即当我们的y == 0或者是x == y的时候就作为递归的退出条件,否则一直递归调用函数,即fun(x-1,y-1)+fun(x-1,y)。接下来我们来实现一下。

import java.util.Scanner;

/**
 * 杨辉三角
 */
public class Main {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        System.out.println("请输入行数:");
        int s = input.nextInt();
        System.out.println("输出的杨辉三角形为:");
        for (int i = 0; i < s; i++) {
            for (int j = 0; j <= i; j++) {
                int m = fun(i, j);

                System.out.print(m + " ");
            }
            System.out.println();
        }
    }

    public static int fun(int x, int y) {
        // 当递归到两边的时候返回1
        if (y == 0 || x == y) {
            return 1;
        } else {
            return fun(x - 1, y - 1) + fun(x - 1, y);
        }
    }
}

结果:
在这里插入图片描述
BUT
上面这个会超时,所以我们用一个二维数组来实现,这样就不会超时了,

import java.util.Scanner;

/**
 * 杨辉三角
 */
public class Main {
    static int[][] a = new int[35][35];

    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        int s = input.nextInt();
        for (int i = 1; i <= 34; i++) {
            for (int j = 1; j <= i; j++) {
                if (j == 1 || i == j) {
                    a[i][j] = 1;
                } else {
                    a[i][j] = a[i - 1][j - 1] + a[i - 1][j];
                }
            }
        }

        for (int i = 1; i <= s; i++) {
            for (int j = 1; j <= i; j++) {
                System.out.print(a[i][j]+" ");
            }
            System.out.println();
        }
    }
}

力扣原题:https://leetcode-cn.com/problems/pascals-triangle/
题解:

class Solution {
    public List<List<Integer>> generate(int numRows) {
        List<List<Integer>> res = new ArrayList<List<Integer>>();
        for(int i=0;i<numRows;i++){
            List<Integer> ret = new ArrayList<>();
            for(int j=0;j<=i;j++){
                if(j==0 || j==i){
                    ret.add(1);
                }else{
                    ret.add(res.get(i-1).get(j-1)+res.get(i-1).get(j));
                }
            }
            res.add(ret);
        }
        return res;
    }
}

借鉴:https://www.bilibili.com/video/BV1u5411H7jD

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值