Tuesday, September 23, 2014

Leetcode: Pascal's Triangle

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]
]
Understand the problem:
The crux of the problem is to understand what is the "Pascal's triangle"?


As is shown in the figure above, each number in the triangle is the sum of the two directory above it. So we can use this property to generate the result.

Solution:
public class Solution {
    public List<List<Integer>> generate(int numRows) {
        List<List<Integer>> result = new ArrayList<List<Integer>>();
        
        if (numRows <= 0) {
            return result;
        }
        
        List<Integer> temp = new ArrayList<Integer>();
        temp.add(1);
        result.add(temp);
        
        if (numRows == 1) {
            return result;
        }
        
        for (int i = 2; i <= numRows; i++) {
            List<Integer> curRow = new ArrayList<Integer>();
            curRow.add(1);
            for (int j = 1; j < i - 1; j++) {
                curRow.add(result.get(result.size() - 1).get(j - 1) + result.get(result.size() - 1).get(j));
            }
            curRow.add(1);
            result.add(curRow);
        }
        
        return result;
    }
}


















No comments:

Post a Comment