LeetCode118.杨辉三角

给定一个非负整数 numRows,生成杨辉三角的前 numRows 行。

在杨辉三角中,每个数是它左上方和右上方的数的和。

示例:

输入: 5
输出:
[
     [1],
    [1,1],
   [1,2,1],
  [1,3,3,1],
 [1,4,6,4,1]
]

解析:帕斯卡三角,又称杨辉三角,给一个行数,输出杨辉三角,需要结合杨辉三角的性质。我们主要根据这条性质来产生结果:每个数字等于上一行的左右两个数字之和。可用此性质写出整个杨辉三角。即第n+1行的第i个数等于第n行的第i-1个数和第i个数之和。
class Solution {
    public List<List<Integer>> generate(int numRows) {
        List<List<Integer>> res = new ArrayList<List<Integer>>();
        List<Integer> list = new ArrayList<>();
        for (int i=0;i<numRows;i++) {
            list.add(0,1);
            for (int j=1;j<list.size()-1;j++) {
                list.set(j,list.get(j)+list.get(j+1));
                
            }
            res.add(new ArrayList<>(list));
            
        }
        return res;
    }
}



猜你喜欢

转载自www.cnblogs.com/airycode/p/9776678.html