119. Pascal's Triangle II

Problem:
Given a non-negative index k where k ≤ 33, return the kth index row of the Pascal's triangle.
Note that the row index starts from 0.

In Pascal's triangle, each number is the sum of the two numbers directly above it.
Example:
Input: 3
Output: [1,3,3,1]
Analysis:
Solution:
class Solution {
    public List<Integer> getRow(int rowIndex) {
        List<Integer> prev = new ArrayList<>();
        List<Integer> cur =  new ArrayList<>();
        for (int i = 1; i <= rowIndex + 1; i++) {
            cur =  new ArrayList<>();
            for (int j = 0 ; j < i; j++) {
                if (j == 0 || j == i - 1) {
                    cur.add(1);
                } else {
                    cur.add(prev.get(j - 1) + prev.get(j));
                }
            }
            prev = cur;
        }       
        return cur;
    }
}

评论

此博客中的热门博文

663. Equal Tree Partition

776. Split BST

426. Convert Binary Search Tree to Sored Doubly Linked List