[LeetCode]第二十一题 :帕斯卡三角 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?

题目描述:

给出一个非负的索引k(k小于等于33),返回第k行的帕斯卡三角的数

注意行索引从0开始

另外:

你的解法的空间复杂度能否为n

题目解法:

1.我的解法。其实跟上一题的解法基本相同。索引是从0开始的,所以我先对索引 + 1方便操作;剩下的跟上一题思路完全一样,不同点在于返回的值不同。代码如下:


class Solution {
    public List<Integer> getRow(int rowIndex) {
        rowIndex += 1;
        List<Integer> list= new ArrayList();
        if(rowIndex < 1) return list;
        int[] tempArray = new int[rowIndex]; 
        for(int i = 1;i <= rowIndex;i++) {
            list= new ArrayList();
            for(int j = 1; j <= i;j++) {
                if(j == 1) list.add(1);
                else if(j == i) list.add(1);
                else {
                    int temp = tempArray[j - 2] + tempArray[j - 1];
                    list.add(temp);
                }
                
            }
            for(int k = 0;k < list.size();k++) {
                tempArray[k] = list.get(k);
            }
        }
        return list;
    }
}

发布了61 篇原创文章 · 获赞 2 · 访问量 8741

猜你喜欢

转载自blog.csdn.net/woaily1346/article/details/80941157