wayetan
12/28/2013 - 5:06 AM

Pascal's Triangle

Pascal's Triangle

/**
 * 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) {
        ArrayList<Integer> res = new ArrayList<Integer>();
        if(rowIndex == 0){
            res.add(1);
            return res;
        }
        // Initialization
        res.add(1);
        res.add(1);
        for(int i = 2; i <= rowIndex; i++){
            res.add(1, res.get(0) + res.get(1));
            for(int j = 2; j < res.size() - 1; j++){
                res.set(j, res.get(j) + res.get(j + 1));
            }
        }
        return res;
    }
}
/**
 * Pascal's Triangle
 * 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]
 * ]
 */
 public class Solution {
    public ArrayList<ArrayList<Integer>> generate(int numRows) {
        ArrayList<ArrayList<Integer>> res = new ArrayList<ArrayList<Integer>>();
        if(numRows == 0) return res;
        // Initialization
        ArrayList<Integer> start = new ArrayList<Integer>();
        start.add(1);
        res.add(start);
        for(int i = 1; i < numRows; i++){
            ArrayList<Integer> prev = res.get(i - 1);
            ArrayList<Integer> curr = new ArrayList<Integer>();
            curr.add(1);
            for(int j = 1; j < i; j++){
                curr.add(prev.get(j - 1) + prev.get(j));
            }
            curr.add(1);
            res.add(curr);
        }
        return res;
    }
}