LeetCode-118-Pascal's Triangle(帕斯卡的三角形)

Q:

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

Analysis:

基础的算法问题,中间元素值等于“肩上”两元素之和。

Code:

class Solution {
    public List<List<Integer>> generate(int numRows) {
        List<List<Integer>> out = new ArrayList<List<Integer>>();
        if (numRows == 0) {
            return out;
        } else {
            for (int i = 1; i <= numRows; i++) {
                ArrayList<Integer> in = new ArrayList<Integer>();
                for (int j = 0; j < i; j++) {
                    if (j == 0 || j == i - 1) {
                        in.add(1);
                    } else {
                        in.add(out.get(i - 2).get(j - 1) + out.get(i - 2).get(j));
                    }
                }
                out.add(in);
            }
        }
        return out;
    }
}

猜你喜欢

转载自blog.csdn.net/renxingkai/article/details/77399035