Thursday, January 1, 2015

Pascal's Triangle (LeetCode Array)

Question: 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]
]

Idea: Brute force. Generate the triangle row by row.

Time: O(n^n) Space: O(n^n)

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

No comments:

Post a Comment