Last active
February 22, 2016 02:40
-
-
Save charlespunk/4700437 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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] | |
] |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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