Leetcode: Pascal's Triangle II

来源:互联网 发布:mac的照片导入ps 编辑:程序博客网 时间:2024/06/11 22:06

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?

To use only O(k) extra space, the key is to use a parameter to store the previous value at previous position, and thus reuse the arraylist in each loop. 

public class Solution {    public ArrayList<Integer> getRow(int rowIndex) {        ArrayList<Integer> res = new ArrayList<Integer>();        if (rowIndex < 0) {            return res;        }                res.add(1);        for (int i = 1; i <= rowIndex; i++) {            int pre = 1;            for (int j = 1; j <= i; j++) {                if (j == i) {                    res.add(1);                } else {                    int curr = res.get(j);                    res.set(j, pre + curr);                    pre = curr;                }            }        }                return res;    }}


0 0
原创粉丝点击