打开APP
userphoto
未登录

开通VIP,畅享免费电子书等14项超值服

开通VIP
118 DIY LeetCode – Pascal’s Triangle (Java)
Given numRows, generate the first numRows of Pascal's triangle. For example, given numRows = 5, the result should be:
[ [1], [1,1], [1,2,1], [1,3,3,1], [1,4,6,4,1]]Java Solution
public ArrayList<ArrayList<Integer>> generate(int numRows) { ArrayList<ArrayList<Integer>> result = new ArrayList<ArrayList<Integer>>(); if (numRows <= 0) return result;  ArrayList<Integer> pre = new ArrayList<Integer>(); pre.add(1); result.add(pre);  for (int i = 2; i <= numRows; i++) { ArrayList<Integer> cur = new ArrayList<Integer>();  cur.add(1); //first for (int j = 0; j < pre.size() - 1; j++) { cur.add(pre.get(j) + pre.get(j + 1)); //middle } cur.add(1);//last  result.add(cur); pre = cur; }  return result;}
自己写的
public class Solution { public List<List<int>> Generate(int numRows) { List<List<int>> ret=new List<List<int>>(); if(numRows==0) { return ret; } List<int> first=new List<int>(); first.Add(1); ret.Add(first); for(int i=2;i<=numRows;i++) { List<int> cur=new List<int>(); cur.Add(1); for(int j=0;j<first.Count-1;j++) { cur.Add(first[j]+first[j+1]); } cur.Add(1); ret.Add(cur); first=cur; } return ret; }}
本站仅提供存储服务,所有内容均由用户发布,如发现有害或侵权内容,请点击举报
打开APP,阅读全文并永久保存 查看更多类似文章
猜你喜欢
类似文章
【热】打开小程序,算一算2024你的财运
47. 全排列 II
56. 合并区间
LeetCode——118. 杨辉三角
【小Y学算法】⚡️每日LeetCode打卡⚡️——33.杨辉三角
android平板上的GridView视图缓存优化
391,回溯算法求组合问题
更多类似文章 >>
生活服务
热点新闻
分享 收藏 导长图 关注 下载文章
绑定账号成功
后续可登录账号畅享VIP特权!
如果VIP功能使用有故障,
可点击这里联系客服!

联系客服