Leetcode 118. 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]
]

解法一

class Solution {
    public List<List<Integer>> generate(int numRows) {
        List<List<Integer>> list = new ArrayList<>();
        if (numRows == 0) 
            return list;
        List<Integer> tmp = new ArrayList<>();
        for (int i = 0; i < numRows; i++) {
            tmp.add(0, 1);
            for (int j = 1; j < tmp.size() - 1; j++) {
                tmp.set(j, tmp.get(j) + tmp.get(j + 1));
            }
            list.add(new ArrayList<>(tmp));
        }
        return list;
    }
}

解法二

class Solution {
    public List<List<Integer>> generate(int numRows) {
        List<List<Integer>> list = new ArrayList<>();
        if (numRows == 0) 
            return list;
        int[][] result = new int[numRows][];
        int[] tmp = new int[1];
        tmp[0] = 1;
        result[0] = tmp;
        for (int i = 0; i < numRows; i++) {
            tmp = new int[i + 1];
            tmp[0] = 1;
            tmp[tmp.length - 1] = 1;
            for (int j = 1; j < tmp.length - 1; j++) {
                tmp[j] = result[i-1][j - 1] +result[i-1][j];
            }
            result[i] = tmp;
        }
        return (List)Arrays.asList(result);

    }
}

猜你喜欢

转载自blog.csdn.net/lutte_/article/details/79551647