2014年1月16日星期四

LeetCoder - 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>> ret = new ArrayList<ArrayList<Integer>>();
        if(numRows==0) {
            return ret;
        }
        ArrayList<Integer> first = new ArrayList<Integer>();
        first.add(1);
        ret.add(first);
        for(int i=1;i<numRows;i++) {
            ArrayList<Integer> last = ret.get(ret.size()-1);
            ArrayList<Integer> cur = new ArrayList<Integer>();
            for(int j=0;j<=last.size();j++) {
                int a = 0;
                if(j-1>=0) {
                    a = last.get(j-1);
                }
                int b = 0;
                if(j<last.size()) {
                    b = last.get(j);
                }
                cur.add(a+b);
            }
            ret.add(cur);
        }        
        return ret;
    }
}

没有评论:

发表评论