Saturday, January 10, 2015

LeetCode 118: 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]
]
public class Solution {
    public List<List<Integer>> generate(int numRows) {
        List<List<Integer>> result = new LinkedList<>();
        
        for (int i = 0; i < numRows; i++)
        {
            List<Integer> row = new LinkedList<>();
            
            for (int j = 0; j <= i; j++)
            {
                if (j==0 || j==i)
                    row.add(1);
                else if (!result.isEmpty())
                {
                    int first = result.get(result.size()-1).get(j-1);
                    int second = result.get(result.size()-1).get(j);
                    row.add(first+second);
                }
            }
            
            result.add(row);
        }
        
        return result;
    }
}

No comments:

Post a Comment