Skip to content

Instantly share code, notes, and snippets.

@charlespunk
Last active February 22, 2016 02:40
Show Gist options
  • Save charlespunk/4700437 to your computer and use it in GitHub Desktop.
Save charlespunk/4700437 to your computer and use it in GitHub Desktop.
Pascal's Triangle Oct 28 '12
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 ArrayList<ArrayList<Integer>> generate(int numRows) {
// Start typing your Java solution below
// DO NOT write main() function
ArrayList<ArrayList<Integer>> result = new ArrayList<ArrayList<Integer>>();
if(numRows == 0) return result;
for(int i = 0; i < numRows; i++){
ArrayList<Integer> thisRow = new ArrayList<Integer>();
for(int j = 0; j <= i; j++){
if(j == 0) thisRow.add(1);
else if(j < i){
int thisNum = result.get(i - 1).get(j - 1) + result.get(i - 1).get(j);
thisRow.add(thisNum);
}
else if(j == i) thisRow.add(1);
}
result.add(thisRow);
}
return result;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment