Leetcode: Pascal's Triangle II

来源:互联网 发布:为什么雷姆受欢迎 知乎 编辑:程序博客网 时间:2024/05/02 05:41

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 ArrayList<Integer> getRow(int rowIndex) {// Start typing your Java solution below// DO NOT write main() functionint[] res = new int[rowIndex + 1];        res[0] = 1;for(int i = 1; i <= rowIndex; i++){for(int j = i; j > 0; j--){if(j == i)res[j] = 1;elseres[j] = res[j - 1] + res[j];}}ArrayList<Integer> res_list = new ArrayList<Integer>();for(int i = 0; i < res.length; i++)res_list.add(res[i]);return res_list;}}