LeetCode-118.杨辉三角(相关话题:数组)

Java代码:

class Solution {
    public List<List<Integer>> generate(int numRows) {
        List<List<Integer>> res = new ArrayList<>(numRows);
        if(numRows > 0){
            List<Integer> l0 = new ArrayList<>();
            l0.add(1);
            res.add(l0);
            if(numRows > 1){
                List<Integer> l1 = new ArrayList<>();
                l1.add(1);
                l1.add(1);
                res.add(l1);
            }
            if(numRows > 2){
                for(int i = 2; i < numRows; i++){
                    List<Integer> tmp = new ArrayList<>(i+1);
                    tmp.add(1);
                    for(int j = 1; j < i; j++){
                        tmp.add(res.get(i-1).get(j-1) + res.get(i-1).get(j));
                    }
                    tmp.add(1);
                    res.add(tmp);
                }
            }
        }
        return res;
    }
}

猜你喜欢

转载自blog.csdn.net/weixin_38823568/article/details/83187130