Pascal's Triangle(LeetCode)

题目:

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


题目分析:

题目输入一个整数numRows,要求生成numRows行的Pascal三角。



思路:

  1. 对于第n-1行,用一个数组temp[]记录为:[0, 第n-1行, 0]。即在第n-1行两边各加一个0。
  2. 对于第n行,其第i个元素即为temp[i] + temp[i+1]

 


注意点:

  1. 对于numRows == 0,要返回一个空数组"[]",而非“null”
  2. 注意在更新temp的时候,各个变量 i,j 等等和上一行、temp之间的关系不要搞错
  3. 对于范式List<List<Integer>> 
    • 其实例化的时候不能直接List<List<Integer>> result0 = new ArrayList<ArrayList<Integer>>()
    • 必须先List<List<Integer>> result0 = new ArrayList<List<Integer>>()
    • 然后对于result0的元素thisLine实例化时使用:List<Integer> thisLine = new ArrayList<Integer>(),即可让List<List<Integer>>中元素为ArrayList类



代码:

public class Solution {
    public List<List<Integer>> generate(int numRows) {
        if(numRows < 0){
            return null;
        }
        if (numRows == 0){
            List<List<Integer>> result0 = new ArrayList<List<Integer>>();
            //List<Integer> thisLine0 = new ArrayList<Integer>();
            //thisLine0.add();
            //result0.add(thisLine0);
            return result0;
        }
        List<List<Integer>> result = new ArrayList<List<Integer>>();
        List<Integer> thisLine = new ArrayList<Integer>(1);
        thisLine.add(1);//generate the 1st row
        result.add(thisLine);
        int[] temp = new int[numRows + 2];//temp need to store one "0" at both the left side and the right side.
        temp[0] = 0;//initiate the temp[]
        temp[1] = 1;
        temp[2] = 0;
        //generate 2nd row and the latters
        for (int i = 1; i < numRows; i++){
            thisLine = new ArrayList<Integer>(i + 1);
            int j;
            for (j = 0; j <= i; j++){
                thisLine.add(j,temp[j] + temp[j+1]);
            }
            result.add(thisLine);
            //update the temp[]
            for (j =1; j <= i + 1; j++){
                temp[j] = thisLine.get(j - 1);
            }
            temp[j] = 0;
        }
        return result;
    }
}




  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值