java中leetcode之用Arraylist List實現楊輝三角
阿新 • • 發佈:2019-01-09
要用java ArrayLIsts實現下面的形式,題目是在leetcode上看到的,
1
1 1
1 2 1
1 3 3 1
具體看看用程式碼怎麼實現把:
結果:package excise; import java.util.List; import java.util.ArrayList; import java.util.LinkedList; import java.util.Iterator; public class T020 { public static void main(String args[]){ Iterator<List<Integer>> iter=caculate(10).iterator(); while(iter.hasNext()){ System.out.println(iter.next()); } } public static List<List<Integer>> caculate(int num){ List<List<Integer>> ans=new ArrayList<List<Integer>>(); if(num<=0){ return ans; }else{ List<Integer> bns=new ArrayList<Integer>(); bns.add(1); ans.add(bns); for(int i=1;i<num;i++){ List<Integer> temp=ans.get(i-1); LinkedList<Integer> link=new LinkedList<Integer>(); link.addFirst(1); for(int j=1;j<i;j++){ link.addFirst(temp.get(j-1)+temp.get(j)); } link.addFirst(1); ans.add(link); } return ans; } } }
[1]
[1, 1]
[1, 2, 1]
[1, 3, 3, 1]
[1, 4, 6, 4, 1]
[1, 5, 10, 10, 5, 1]
[1, 6, 15, 20, 15, 6, 1]
[1, 7, 21, 35, 35, 21, 7, 1]
[1, 8, 28, 56, 70, 56, 28, 8, 1]
[1, 9, 36, 84, 126, 126, 84, 36, 9, 1]