Saturday, November 21, 2015

[leetcode]pascal's triangle

注意off by 1 还有里面for loop别加错index
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
public class Solution {
    public List<List<Integer>> generate(int numRows) {
        List<List<Integer>> result = new ArrayList<List<Integer>>();
        if (numRows <= 0) return result;
        List<Integer> firstRow = new ArrayList<Integer>();
        firstRow.add(1);
        result.add(firstRow);
        for (int i = 1; i < numRows; i++){
            List<Integer> prevRow = result.get(i-1);
            List<Integer> current = new ArrayList<Integer>();
            current.add(1);
            for (int j = 1; j <= i; j++){
                int upLeft = prevRow.get(j-1);
                int upper = prevRow.size() == j?0:prevRow.get(j);
                current.add(upLeft+upper);
            }
            result.add(current);
        }
        return result;
    }
}

No comments:

Post a Comment