LeetCode Pascal's Triangle II

来源:互联网 发布:mac os 软件下载 编辑:程序博客网 时间:2024/06/13 16:00

Pascal's Triangle II

 Total Accepted: 17645 Total Submissions: 57815My Submissions

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?

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


0 0