119. Pascal's Triangle II

本文提供了一种高效算法来求解帕斯卡三角形的第K行,采用Java实现,讨论了时间复杂度为O(k²)和空间复杂度为O(k)的解决方案,并给出了详细的代码示例。

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

题目:

Given an index k, return the kth row of the Pascal's triangle.

For example, given k = 3,
Return [1,3,3,1].

链接: http://leetcode.com/problems/pascals-triangle-ii/

题解:

跟上题一样。

Time Complexity - O(n),Space Complexity - O(1)。

public class Solution {
    public List<Integer> getRow(int rowIndex) {
        List<Integer> res = new ArrayList<>();
        
        for(int i = 0; i <= rowIndex; i++) {
            res.add(0, 1);
            
            for(int j = 1; j < res.size() - 1; j++)
                res.set(j, res.get(j) + res.get(j + 1));    
        }
        
        return res;
    }
}

 

二刷:

和Pascals Triangle I一样。主要的点是 k = 0的时候, 结果等于1, k = 1的时候,结果为11。 题目没说清楚,不过并没有什么影响,知道方法就可以了。

Java:

Time Complexity - O(n),Space Complexity - O(k)。

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

 

三刷:

上面的复杂度算错了。 同时要注意k = 0的时候结果为{1},以此类推。

Java:

Time Complexity - O(k ^2),Space Complexity - O(k)。

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

 

Update:

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

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值