LeetCode(30)-Pascal's 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]
]

思路

  • 題意是要用數組表示帕斯卡三角形
  • 輸入一個數值,顯示相應行數的【帕斯卡三角形
  • 根據下一行和上一行的遞推公式來處理
  • 設置一個變量fisrt來記錄上一行的數據,最新一行的是新建的
  • -

代碼

public class Solution {
    public List<List<Integer>> generate(int numRows) {
         List<List<Integer>> all = new ArrayList<List<Integer>>();
        List<Integer> first = new ArrayList<Integer>();
        if(numRows == 0){
            return all;
        }
        if(numRows == 1){
            List<Integer> a1 = new ArrayList<Integer>();
            a1.add(1);
            all.add(a1);
            return all;
        }
        if(numRows > 1){
            List<Integer> a2 = new ArrayList<Integer>();
            a2.add(1);
            all.add(a2);
        }
        for(int i = 1;i < numRows;i++){
            List<Integer> next = new ArrayList<Integer>();
            next.clear();
            next.add(1);
            for(int a = 1;a < i;a++){
                if(a-1 >= 0 )
                next.add(first.get(a-1)+first.get(a));
            }
            next.add(1);
            all.add(next);
            first.clear();
             if(next != null){
                for(int o = 0;o < next.size();o++){
                    first.add(next.get(o));
                }
            }
        }
        return all;
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章