Skip to content

Instantly share code, notes, and snippets.

@charlespunk
Last active December 12, 2015 02:38
Show Gist options
  • Save charlespunk/4700440 to your computer and use it in GitHub Desktop.
Save charlespunk/4700440 to your computer and use it in GitHub Desktop.
Pascal's Triangle II Oct 29 '12
Given an index k, return the kth row of the Pascal's triangle.
For example, given k = 3,
Return [1,3,3,1].
Note:
Could you optimize your algorithm to use only O(k) extra space?
public class Solution {
public ArrayList<Integer> getRow(int rowIndex) {
// Start typing your Java solution below
// DO NOT write main() function
ArrayList<Integer> lastLine = new ArrayList<Integer>();
lastLine.add(1);
if(rowIndex == 0) return lastLine;
ArrayList<Integer> thisLine = new ArrayList<Integer>();
for(int i = 1; i <= rowIndex; i++){
for(int j = 0; j <= i; j++){
if(j == 0) thisLine.add(1);
else if(j < i){
thisLine.add(lastLine.get(j - 1) + lastLine.get(j));
}
else if(j == i){
thisLine.add(1);
}
}
lastLine = thisLine;
thisLine = new ArrayList<Integer>();
}
return lastLine;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment