[LeetCode] 119. Pascal's Triangle II Java

题目:

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

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

Note:
Could you optimize your algorithm to use only O(k) extra space?

题意及分析:求杨辉三角的第k行,第一行下标为0.

代码:

class Solution {
    public List<Integer> getRow(int rowIndex) {
        List<Integer> list = new ArrayList<>();
        for(int i=1;i<=rowIndex+1;i++){       //分别求出每一行
            List<Integer> newList = new ArrayList<>();
            newList.add(0,1);  //第一个数为1
            for(int k=1;k<i-1;k++){
                newList.add(k,list.get(k)+list.get(k-1));
            }
            if(i>1)newList.add(1);
            list = newList;
        }
        return list;
    }
}

 或者,每一行从后往前求的话可以复用,不用新建一个临时list,可以节约空间

class Solution {
    public List<Integer> getRow(int rowIndex) {     //获取第杨辉三角的第rowIndex行,空间复杂度为o(rowIndex)
        List<Integer> list = new ArrayList<>();
        for(int i=0;i<rowIndex+1;i++){       //分别求出每一行
            list.add(1);
            for(int k=i-1;k>0;k--){
                list.set(k,list.get(k)+list.get(k-1));
            }
        }
        return list;
    }
}

 

原文地址:https://www.cnblogs.com/271934Liao/p/7813577.html