Leetcode: Pascal's Triangle

本文介绍了一种生成帕斯卡三角的算法实现。通过Java代码示例展示了如何根据输入的行数生成指定行数的帕斯卡三角,并返回每一行的元素列表。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Given numRows, generate the first numRows of Pascal's triangle.

For example, given numRows = 5,
Return

[
     [1],
    [1,1],
   [1,2,1],
  [1,3,3,1],
 [1,4,6,4,1]
]

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



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值