您的位置:首页 > 其它

[118] Pascal's Triangle

2016-07-19 19:01 429 查看

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];
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息