118. Pascal‘s Triangle [Easy]

杨辉三角 

/**
 * 自己的代码,感觉区分的特殊情况太多了,应该有更简洁的
 * Runtime: 0 ms, faster than 100.00%
 * Memory Usage: 37 MB, less than 48.58%
 */
class Solution {
    public List<List<Integer>> generate(int numRows) {
        List<List<Integer>> res = new ArrayList();
        List<Integer> first = new ArrayList<Integer>();
        first.add(1);
        res.add(first);
        for (int i = 2; i <= numRows; i++) {
            List<Integer> currList = new ArrayList<Integer>();
            currList.add(1);
            for (int j = 1; j < i - 1; j++) {
                currList.add(res.get(i - 2).get(j - 1) + res.get(i - 2).get(j));
            }
            currList.add(1);
            res.add(currList);
        }
        return res;
    }
}
/**
 * 把第一行、每一行首尾这样的特殊情况都写在内层循环里,简洁一点但会在循环中增加判断
 * Runtime: 0 ms, faster than 100.00%
 * Memory Usage: 36.9 MB, less than 65.75%
 */
class Solution {
    public List<List<Integer>> generate(int numRows) {
        List<List<Integer>> res = new ArrayList();
        for (int i = 0; i < numRows; i++) {
            List<Integer> currL = new ArrayList();
            for (int j = 0; j <= i; j++) {
                if (j == 0 || j == i) {
                    currL.add(1);
                } else {
                    currL.add(res.get(i - 1).get(j - 1) + res.get(i - 1).get(j));
                }
            }
            res.add(currL);
        }
        return res;
    }
}
/**
 * 讨论区的做法,用一个ArrayList不断更新为每一行,每行计算完将其当前状态新建为一个list添加到res
 * Runtime: 0 ms, faster than 100.00%
 * Memory Usage: 36.6 MB, less than 95.08%
 */
class Solution {
    public List<List<Integer>> generate(int numRows) {
        List<List<Integer>> res = new ArrayList();
        List<Integer> row = new ArrayList();
        for (int i = 0; i < numRows; i++) {
            row.add(0, 1); // add 1 in the head, make both the first element and the amount of elements in the new row right
            for (int j = 1; j < row.size() - 1; j++) { // don't have to set the last element, which would always be 1
                row.set(j, row.get(j) + row.get(j + 1));
            }
            res.add(new ArrayList(row));
        }
        return res;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值