脚本宝典收集整理的这篇文章主要介绍了【LeetCode】#118. 杨辉三角,脚本宝典觉得挺不错的,现在分享给大家,也给大家做个参考。
给定一个非负整数 numRows
,生成「杨辉三角」的前 numRows
行。
在「杨辉三角」中,每个数是它左上方和右上方的数的和。
示例 1:
输入: numRows = 5 输出: [[1],[1,1],[1,2,1],[1,3,3,1],[1,4,6,4,1]]
示例 2:
输入: numRows = 1 输出: [[1]]
方法一根据每个数是它左上方和右上方的数的和。 class Solution { public List<List<Integer>> generate(int numRows) { List<List<Integer>> a = new ArrayList<List<Integer>>(); for(int i = 0; i < numRows; i++){ List<Integer> b = new ArrayList<Integer>(); for(int j = 0; j <= i; j++){ if(j == 0 || i == j){ b.add(1); }else{ b.add(a.get(i - 1).get(j) + a.get(i - 1).get(j - 1)); } } a.add(b); } return a; } }
知识点:
List的泛型内也可以添加List
总结:
无
以上是脚本宝典为你收集整理的【LeetCode】#118. 杨辉三角全部内容,希望文章能够帮你解决【LeetCode】#118. 杨辉三角所遇到的问题。
本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。