118.Pascal's Triangle

題目連接:https://leetcode.com/problems/pascals-triangle/description/ide

題目大意:給出楊輝三角的行數,打印其楊輝三角。例子以下:spa

法一:直接模擬(傳說這就是dp),楊輝三角的規律是:每一個數都是其上兩個元素的和。注意內層的list在每一次for循環後須要清空數值,其清空方法能夠有clear()和removeAll(),但我都沒有成功,因此我採用了直接new的辦法。代碼以下(耗時1ms):3d

 1     public List<List<Integer>> generate(int numRows) {
 2         List<List<Integer>> list = new ArrayList<List<Integer>>();
 3         for(int i = 1; i <= numRows; i++) {
 4             List<Integer> listIn = new ArrayList<Integer>();
 5             for(int j = 0; j < i; j++) {
 6                 if(j == 0 || j == i - 1) {
 7                     listIn.add(1);
 8                 }
 9                 else {
10                     listIn.add(list.get(i-2).get(j-1) + list.get(i-2).get(j));
11                 }
12             }
13             list.add(listIn);
14         }
15         return list;
16     }
View Code
相關文章
相關標籤/搜索