Thursday, March 7, 2013

[LeetCode] Pascal's Triangle II

Thought:
Calculate from the end to the front.

Code:
public class Solution {
    public ArrayList<Integer> getRow(int rowIndex) {
        if (rowIndex == 0) {
            ArrayList<Integer> result = new ArrayList<Integer>();
            result.add(1);
            return result;
        }else {
            ArrayList<Integer> result = getRow(rowIndex - 1);
            result.add(1);
            for (int i = rowIndex - 1; i > 0; i--) {
                result.set(i, result.get(i) + result.get(i - 1));
            }
            result.set(0,1);
            return result;
        }
    }
}

No comments:

Post a Comment