杨辉三角形

  • 什么是杨辉三角形?
    1
    1 1
    1 2 1
    1 3 3 1
    1 4 6 4 1

上面的就是几组杨辉三角形的数据,那么从数据中可以发现以下几个规律:

  • 第一行数据固定,只有1个1;
  • 第二行数据固定,有2个1;
  • 第i行必定有i列数据;
  • 从第三行开始,每行的第一列和最后一列的数据都是1;
  • 第i行第j列的数据 = 第(i-1)行第(j-1)列的数据+ 第(i-1)行第j列的数据;
    代码:
public class YangHui {

    public static List<List<Integer>> generate(int numRows){
       //判断numRows的合法性
        if (numRows <= 0){
            return null;
        }
        //定义result用来保存要求的第i行的数据
        List<List<Integer>> result = new ArrayList<>();
        //定义firstLine来保存第1行的数据
        List<Integer> firstLine = new ArrayList<>();
        firstLine.add(1);
        result.add(firstLine);
        if (numRows == 1){
            return result;
        }
        List<Integer> secondLine = new ArrayList<>();
        secondLine.add(1);
        secondLine.add(1);
        result.add(secondLine);
        if (numRows == 2){
            return result;
        }
        for (int row = 3; row <= numRows; row++) {
            //定义prevLine来保存前一行的数据,row-1表示前一行,但由于下标是从0开始的,因此row-1行的下标还要-1
            List<Integer> prevLine = result.get((row-1)-1);
            List<Integer> curLine = new ArrayList<>();
            curLine.add(1);
            for (int col = 2; col < row; col++) {
                int curNum = prevLine.get((col-1)-1)+ prevLine.get(col-1);
                curLine.add(curNum);
            }
            curLine.add(1);
            result.add(curLine);
        }
        return result;
    }

    public static void main(String[] args) {
        System.out.println(generate(4));
    }
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值