leetcode--Pascal's Triangle II

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?


题意:给定行数(从0开始),求帕斯卡三角形中该行。

分类:数组


解法1:每次只保留上一行即可。

public class Solution {
    public List<Integer> getRow(int rowIndex) {
        ArrayList<Integer> next = new ArrayList<Integer>();  
        ArrayList<Integer> res = new ArrayList<Integer>();  
        for(int i=1;i<=rowIndex+1;i++){  
            next.add(1);  
            for(int j=1;j<i-1;j++){  
                next.add(res.get(j-1)+res.get(j));  
            }  
            if(i!=1) next.add(1);  
            res.clear();
            res.addAll(next);
            next.clear();
        }  
        return res;  
    }
}

你可能感兴趣的:(leetcode--Pascal's Triangle II)