Pascal's Triangle

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

Hide Tags
  Array













分析:给你一个行数(整数)numRows,生成一个numRows排的杨辉三角


解法:
因为是直接返回一个2维列表,直接算即可
用一个array来保存上一排的数字。一个last变量保存被更新,但需要计算下一个数的数,如上图,计算绿色的方格需要上一排两个数,但是上面的2已经被更新为了下一排的3.所以last值为2.

public static List<List<Integer>> generate(int numRows) {

List<List<Integer>> result = new ArrayList<List<Integer>>();

List<Integer> first = new ArrayList();

if (numRows==0) return result;

first.add(1);

result.add(first);

if (numRows==1) return result;

for (int i = 1; i < numRows; i++) {

ArrayList<Integer> each = new ArrayList();

each.add(1);// 先把第一个元素填充好

for (int j = 1; j < i; j++) {

// 从第二个元素开始,其等于上一个list的第j-1和j元素之和

each.add(result.get(i - 1).get(j - 1)

+result.get(i - 1).get(j));

}

// 第i个元素还是1

each.add(1);

result.add(each);

}

return result;

}



注意的是需要对输入为0 和1 的情况考虑周详。

List<List<Integer>> 初始化de时候也要尤为注意,List是个接口。

List<List<Integer>> result = new ArrayList<List<Integer>>();

List<Integer> first = new ArrayList();


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值