LeetCode刷题EASY篇计算杨辉三角第k行. Pascal's Triangle II

题目

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) {
        Integer[] array=new Integer[rowIndex+1];
        Arrays.fill(array, 0);
        array[0]=1;
        for(int i=1;i<=rowIndex;i++){
            //始终是一个数组,倒序更新,第一个元素始终为1,无需更新,所以j>0
            for(int j=i;j>0;j--){
                array[j]=array[j]+array[j-1];
            }  
        }
        return Arrays.asList(array);
        
        
    }
}

猜你喜欢

转载自blog.csdn.net/hanruikai/article/details/84863088
今日推荐