《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