Pascal’s Triangle, Leetcode 解题笔记

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]
]

这题很没意思,应该是考察list操作,就是每行开头结尾都是1,中间元素value[i]是上一行的value[i] + value[i-1]。

public class Solution {
    public ArrayList<ArrayList<Integer>> generate(int numRows) {
        ArrayList<ArrayList<Integer>> ret = new ArrayList<ArrayList<Integer>>();
        ArrayList<Integer> row = new ArrayList<Integer>();
        if(numRows == 0) return ret;
        row.add(1);
        ret.add(row);
        if(numRows == 1) return ret;
        for(int i = 1; i < numRows; i++){
            row = new ArrayList<Integer>();
            row.add(1);
            for(int j = 0; j < ret.get(ret.size()-1).size()-1; j++){
                row.add(ret.get(ret.size()-1).get(j) + ret.get(ret.size()-1).get(j+1));
            }
            row.add(1);
            ret.add(new ArrayList<Integer>(row));
        }
        return ret;
    }
}
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s