leetcode Pascal's Triangle II题解

本文详细解析了如何使用Java编程解决杨辉三角问题,通过动态更新两层数据的策略,仅需O(k)额外空间即可高效求解指定行的元素。

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

题目描述:

Given a non-negative index k where k ≤ 33, return the kth index row of the Pascal's triangle.

Note that the row index starts from 0.


In Pascal's triangle, each number is the sum of the two numbers directly above it.

Example:

Input: 3
Output: [1,3,3,1]

Follow up:

Could you optimize your algorithm to use only O(k) extra space?

中文理解:杨辉三角,返回下标为k的层,第一层下标为0,依次类推。

解题思路:从上面动图可以看出来,杨辉三角的每一层仅仅与上一层有关,故仅仅需要保存两层的数据即可。或者可以采用Cn(m)组合数的方法来得到每一个值,仅仅需要O(k)的空间,这次解法采用的是第一种解法。

代码(java):

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

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值