leetcode-帕斯卡三角形

帕斯卡三角形
给定一个非负整数 numRows,生成杨辉三角的前 numRows 行。
示例:
输入: 5
输出:
[
[1],
[1,1],
[1,2,1],
[1,3,3,1],
[1,4,6,4,1]
]
 
思路:利用三角形性质 1*(n-1)*(n-2)/2 *(n-3)/3  * (n-4)/4    和杨辉三角形n行含有n个数字的数学性质。
本题可以通过数学性质来获得求解。代码如下:   注意1*(n-1)*(n-2)/2 *(n-3)/3  * (n-4)/4中Int型数组导致运算结果为0的情况(如2/5=0,1/2=0)
class Solution {
    public List<List<Integer>> generate(int numRows) {
        List<List<Integer>> res=new ArrayList<List<Integer>>();
        for(int i=1;i<=numRows;i++){
            List<Integer> list=new ArrayList();
            list.add(1);
            double temp=1;
            for(int j=1;j<i;j++){
                temp=(temp*(i-j))/j;   //这个地方不能写成temp*=(i-j)/j  因为是Int型 (i-j)/j 会变成0.
                list.add((int)temp);
            }
            
            res.add(list);
        }
        return res;
    }
}

另一种解法根据数组的性质,每一个数字都是上一组的前一个数与后一个数之和。

class Solution {
    public List<List<Integer>> generate(int numRows) {
       List<List<Integer>> pascal = new ArrayList<List<Integer>>();
        ArrayList<Integer> row = new ArrayList<Integer>();
        for (int i = 0; i < numRows; i++) {
            row.add(0, 1);     //(0,1)中的0是索引,1是值。 每一组首先添加1进行运算
            for (int j = 1; j < row.size() - 1; j++)
                row.set(j, row.get(j) + row.get(j + 1));    //上一组前两个数字的和
            pascal.add(new ArrayList<Integer>(row));
        }
        return pascal;
    }
}
class Solution {
    public List<List<Integer>> generate(int numRows) {
       List<List<Integer>> pascal = new ArrayList<List<Integer>>();
        ArrayList<Integer> row = new ArrayList<Integer>();
        for (int i = 0; i < numRows; i++) {
            row.add(0, 1);     //(0,1)中的0是索引,1是值。 每一组首先添加1进行运算
            for (int j = 1; j < row.size() - 1; j++)
                row.set(j, row.get(j) + row.get(j + 1));    //上一组前两个数字的和
            pascal.add(new ArrayList<Integer>(row));
        }
        return pascal;
    }
}
原文地址:https://www.cnblogs.com/patatoforsyj/p/9484442.html