Thursday, April 3, 2014

Pascal's Triangle II @LeetCode

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?
package leetcode;
import java.util.ArrayList;
/**
* Solution: Same to Pascal's Triangle I.
* Use a result to remember the previous line result. Other steps are same to I.
* At first, I'd like to create a rowIndex + 1 size ArrayList. every time I can use it
* to store result. But I can't code it out. this is the real O(k) space.
*
* Every problem with limited space, we need to consider reuse some space we have.
* Like Set Matrix Zeros
*
* @author jeffwan
* @date Apr 3, 2014
*/
public class PascalTriangleII {
public ArrayList<Integer> getRow(int rowIndex) {
ArrayList<Integer> result = new ArrayList<Integer>();
if (++rowIndex == 0) {
return result;
}
result.add(1);
for (int i = 1; i < rowIndex; i++) {
ArrayList<Integer> temp = new ArrayList<Integer>(i + 1);
for (int j = 0; j < i + 1; j++) {
temp.add(-1);
}
temp.set(0, result.get(0));
temp.set(i, result.get(i - 1));
for (int j = 1; j < i; j++) {
temp.set(j, result.get(j - 1) + result.get(j));
}
result = temp;
}
return result;
}
}

No comments:

Post a Comment