Last active
December 12, 2015 02:38
-
-
Save charlespunk/4700440 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 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? |
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<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