leetcode 119. Pascal's Triangle II 杨辉三角2

本文探讨了在给定非负整数k的情况下,如何使用仅O(k)额外空间的算法来找到杨辉三角的第k行。通过两种不同的方法实现,一种是计算整个杨辉三角再取行,另一种是优化后的算法,直接计算目标行,避免了不必要的计算。

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

119 Pascal’s Triangle II
Description:
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?

首先我用了最直接的方法利用杨辉三角的性质计算出整个杨辉三角,然后取最底一行。

class Solution {
    public List<Integer> getRow(int rowIndex) {
        rowIndex=rowIndex+1;
        Integer[][] a = new Integer[rowIndex][rowIndex];
        for(int i=0; i<rowIndex; i++)
            for(int j=0; j<rowIndex; j++){
                a[i][0]=1;
                if(i==j) 
                    a[i][j]=1;
            }                 
        for(int i=2; i<rowIndex; i++)
            for(int j=1; j<i; j++)
                a[i][j]=a[i-1][j-1]+a[i-1][j];
        List<Integer> list = Arrays.asList(a[rowIndex-1]);
        return list;
    }
}

但它把每个数都计算了出来,不符合空间复杂度O(k)…
然后在讨论区发现了更好的方法:

class Solution {
  public List<Integer> getRow(int k) {
        Integer[] arr = new Integer[k + 1];
        Arrays.fill(arr, 0);
        arr[0] = 1;
        for (int i = 1; i <= k; i++) 
            for (int j = i; j > 0; j--) 
                arr[j] = arr[j] + arr[j - 1]; 
        return Arrays.asList(arr);
    }
}

除第一个和最后一个数字之外,其他的数字都是上一行左右两个值之和。我们利用两个for循环,除第一个数为1之外,后面的数都是上一次循环的数值加上它前面位置的数值之和,不停地更新每一个位置的值,便可以得到第n行的数。

关于杨辉三角的更多性质可参考下面的链接:
http://www.cnblogs.com/grandyang/p/4031536.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值