Algorithm-Arrays-6 Kth pascal triangle

本文介绍了一种高效算法来求解帕斯卡三角形的第K行元素值,通过两种方法实现:一种是利用动态规划的思想逐行计算;另一种是通过组合数学的性质直接计算每项值,仅需O(K)额外空间。

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

1. 题目: Kth Row of Pascal’s Triangle

此处有关于该问题的类似解法。

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

Pascal’s triangle : To generate A[C] in row R, sum up A’[C] and A’[C-1] from previous row R - 1.

Example:

Input : k = 3

Return : [1,3,3,1]
NOTE : k is 0 based. k = 0, corresponds to the row [1].
Note:Could you optimize your algorithm to use only O(k) extra space?

输入为第k行,输出改行的元素值(k是从0开始的下标)。

2. 解题思路

1). 法1

public List<Integer> getRow(int rowIndex) {
        ArrayList<Integer> result = new ArrayList<>();
        if (rowIndex < 0)
            return result;
        result.add(1);
        for (int i = 1; i <= rowIndex; i++) {
            // 当前循环的result可由上一层循环的result得到
            for (int j = result.size() - 2; j >= 0; j--) {
                result.set(j + 1, result.get(j + 1) + result.get(j));
            }
            result.add(1);
        }
        return result;
    }

2). 法2

/*
     * C(line, i) = line! / ( (line-i)! * i! ) C(line, i-1) = line! / ( (line -
     * i + 1)! * (i-1)! ) We can derive following expression from above two
     * expressions. C(line, i) = C(line, i-1) * (line - i + 1) / i
     * 
     * So C(line, i) can be calculated from C(line, i-1) in O(1) time
     */
    public ArrayList<Integer> getRow1(int A) {
        ArrayList<Integer> list = new ArrayList<Integer>(A + 1);
        int line = A + 1;
        int C = 1; // used to represent C(line, i)
        for (int i = 1; i <= line; i++) {
            list.add(C); // The first value in a line is always 1
            C = C * (line - i) / i;

        }
        return list;
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值