Sunday, July 5, 2015

Pascal's Triangle | Leetcode

Given numRows, generate the first numRows of Pascal's triangle.

For example, given numRows = 5,

Return
[
     [1],
    [1,1],
   [1,2,1],
  [1,3,3,1],
 [1,4,6,4,1]
]
---

Solution: Start off with the base case, with the first list having only one element "1". For each additional list, put a "1" at the beginning and another "1" at the end. For each element in the middle, add the two adjacent elements from the list at the top to get the element's value.
public class Solution {
    public List<List<Integer>> generate(int numRows) {
        List<List<Integer>> answer = new ArrayList<>();
        if (numRows == 0) return answer;
        answer.add(Arrays.asList(1));
        for (int i = 1; i < numRows; i++) {
            List<Integer> lastList = answer.get(i - 1);
            List<Integer> curList = new ArrayList<>();
            answer.add(curList);
            curList.add(1);
            for (int j = 0; j < lastList.size() - 1; j++) {
                curList.add(lastList.get(j) + lastList.get(j + 1));
            }
            curList.add(1);
        }
        return answer;
    }
}

No comments: