Tuesday, June 3, 2014

Leetcode: Palcal'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]
] 

Solution:

public class Solution {
    public List<List<Integer>> generate(int numRows) {
        List<List<Integer>> solution = new ArrayList<List<Integer>>();
        if (numRows == 0)
            return solution;
        List<Integer> previousRow;
        List<Integer> actualRow = new ArrayList<Integer>();
        actualRow.add(1);
        solution.add(actualRow);
        for(int i=1; i<numRows; i++)
        {
            previousRow = actualRow;
            actualRow = new ArrayList<Integer>();
            actualRow.add(1);
            for(int j=0; j<previousRow.size()-1;j++)
            {
                actualRow.add(previousRow.get(j)+previousRow.get(j+1));
            }
            actualRow.add(1);
            solution.add(actualRow);
        }
        return solution;
    }
}

No comments :

Post a Comment