《leetcode》pascals-triangle(杨辉三角)
生活随笔
收集整理的这篇文章主要介绍了
《leetcode》pascals-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]
]
解析:每一行的首尾都是1,就是构件的中间值需要上一行相邻的数想加得到,具体操作见代码。
import java.util.ArrayList; public class Solution {public ArrayList<ArrayList<Integer>> generate(int numRows) {ArrayList<ArrayList<Integer>> list = new ArrayList<>();if(numRows==0){return list;}ArrayList<Integer> first = new ArrayList<>();first.add(1);list.add(first);if(numRows==1){return list;}for(int i=1;i<numRows;i++){//从第二行开始干起ArrayList<Integer> pre=list.get(i-1);//上一行的数据ArrayList<Integer> temp = new ArrayList<>();//当前需要构件行的信息temp.add(1);//构件首部1for(int k=0;k<pre.size()-1;k++){//中间相邻数相加temp.add(pre.get(k)+pre.get(k+1));}temp.add(1);//构件尾部1list.add(temp);}return list;} }总结
以上是生活随笔为你收集整理的《leetcode》pascals-triangle(杨辉三角)的全部内容,希望文章能够帮你解决所遇到的问题。
- 上一篇: 《leetcode》search-ins
- 下一篇: 《leetcode》valid-pare