杨辉三角java代码_【LeetCode】118. 杨辉三角(Pascal#x27;s Triangle)解题思路
生活随笔
收集整理的這篇文章主要介紹了
杨辉三角java代码_【LeetCode】118. 杨辉三角(Pascal#x27;s Triangle)解题思路
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
題目如下(題目鏈接戳我):
給定一個非負整數 numRows,生成楊輝三角的前 numRows 行。 備注:在楊輝三角中,每個數是它左上方和右上方的數的和。示例: 輸入: 5 輸出: [[1],[1,1],[1,2,1],[1,3,3,1],[1,4,6,4,1] ]也給出了楊輝三角的示例圖:
以下是我的解題思路:
我首先整理了前 5 行楊輝三角的數據;
11 11 2 11 3 3 1 1 4 6 4 1根據題目的返回值要求( List < List < Integer >> )(我在中括號和字母之間故意加了空格),我把每一行看作一個集合,每個元素對應一個下標索引,我把索引也整理了一下;
00 10 1 20 1 2 3 0 1 2 3 4然后得出了以下幾條規律和方法:
思路整理完了,剩下寫代碼就很簡單了。
public List<List<Integer>> generate(int numRows) {List<List<Integer>> list = new ArrayList<>();List<Integer> item;//當前行的集合List<Integer> last = null; //上一行的集合int index = 1; //行號,每行元素個數和行號一致while (index <= numRows) {item = new ArrayList<>();//循環index次,向item中添加元素a:for (int i = 0; i < index; i++) {if(last == null){item.add(1);break a;}else if(i == 0){item.add(1);}else if(i == index - 1){item.add(last.get(i - 1));}else{item.add(last.get(i - 1) + last.get(i));}}last = item;list.add(item);index++;}return list;}提交結果:
執行用時 : 1 ms, 在Pascal's Triangle的Java提交中擊敗了97.86% 的用戶 內存消耗 : 33.6 MB, 在Pascal's Triangle的Java提交中擊敗了39.51% 的用戶總結
以上是生活随笔為你收集整理的杨辉三角java代码_【LeetCode】118. 杨辉三角(Pascal#x27;s Triangle)解题思路的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 多个字段条件相同进行分组并过滤拼装SQL
- 下一篇: 对Kafka的总结