[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]; }
相关文章推荐
- C语言打印杨辉三角示例汇总
- shell 中数学计算总结
- C语言小程序 杨辉三角示例代码
- PHP几个数学计算的内部函数学习整理
- C语言实现杨辉三角实例
- C语言在屏幕上输出杨辉三角
- java使用for循环输出杨辉三角
- 用Python输出一个杨辉三角的例子
- leetcode 179 Largest Number
- leetcode 24 Swap Nodes in Pairs
- leetcode 2 Add Two Numbers 方法1
- leetcode 2 Add Two Numbers 方法2
- 实现杨辉三角
- 2. 计算机语言的发展过程
- leetcode----Longest Substring Without Repeating Characters
- [LeetCode]47 Permutations II
- [LeetCode]65 Valid Number
- [LeetCode]123 Best Time to Buy and Sell Stock III
- [LeetCode] String Reorder Distance Apart
- [LeetCode] Sliding Window Maximum