[118] Pascal's Triangle

1. 题目描述

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

给定一个数值作为行数,求行数为给定数的杨辉三角形(帕斯卡三角形)。

2. 解题思路

杨辉三角形求法如下
杨辉三角动画
具体杨辉三角的定义请见维基百科”杨辉三角形
有了杨辉三角的求法就发现每一行的最左最右值都为1,中间的第i个值为上一行的第i-1个值和第i个值之和。当然这个是从第三行开始的,因为第一第二行都只有元素1。

3. Code

import java.util.ArrayList;
import java.util.List;

public class Solution {
    public List<List<Integer>> generate(int numRows) {
        List<List<Integer>> result = new ArrayList<>();
        if(numRows <= 0){
            return result;
        }
        // [1]
        List<Integer> mid1 = new ArrayList<>();
        mid1.add(1);
        result.add(mid1);
        if(numRows >= 2)
        {
            // [1,1]
            List<Integer> mid2 = new ArrayList<>();
            mid2.add(1);
            mid2.add(1);
            result.add(mid2);
        }
        // 查阅了ArrayList代码发现不能越界,会直接抛出一个IndexOutOfBoundsException的异常
        // 所以真正的开始计算从第三行开始计算才不会越界
        for(int n = 2; n < numRows; ++n)
        {
            List<Integer> mid = new ArrayList<>();
            // first 1
            mid.add(1);
            for(int i = 0; i+1 < n; ++i)
            {
                // 递推关系,拿到上一层的值
                List<Integer> front = result.get(n-1);
                // 上一层的第i个加上第i+1个为当前层的第i个
                mid.add(front.get(i) + front.get(i+1));
            }
            // last 1
            mid.add(1);
            result.add(mid);
        }
        return result;
    }
}
下面附上ArrayList中get方法的实现
    /**
     * Returns the element at the specified position in this list.
     *
     * @param  index index of the element to return
     * @return the element at the specified position in this list
     * @throws IndexOutOfBoundsException {@inheritDoc}
     */
    public E get(int index) {
        // 检查要get的index是否越界
        rangeCheck(index);
        return elementData(index);
    }
    /**
     * Checks if the given index is in range.  If not, throws an appropriate
     * runtime exception.  This method does *not* check if the index is
     * negative: It is always used immediately prior to an array access,
     * which throws an ArrayIndexOutOfBoundsException if index is negative.
     */
    private void rangeCheck(int index) {
        if (index >= size)
        // 抛出了异常
            throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
    }
    // Positional Access Operations

    @SuppressWarnings("unchecked")
    E elementData(int index) {
        // 直接返回当前Array中的元素值
        return (E) elementData[index];
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值