Skip to content

Files

Latest commit

562a409 · Mar 24, 2016

History

History
74 lines (65 loc) · 1.71 KB

118. Pascal's Triangle.md

File metadata and controls

74 lines (65 loc) · 1.71 KB

#118. 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]
]

思路:递归;迭代

Java Solution(Recursion)

ppublic class Solution {
    public List<List<Integer>> generate(int numRows) {
        List<List<Integer>> list = new ArrayList<List<Integer>>();
        List<Integer> inlist = new ArrayList<Integer>();
        if(numRows==0) { }
        else if(numRows==1){
            inlist.add(1);
            list.add(inlist);
        }else if(numRows==2){
            inlist.add(1);
            inlist.add(1);
            list.addAll(generate(1));
            list.add(inlist);
        }else{
        List<Integer> duplist = new ArrayList<Integer>();
        list = generate(numRows-1);
        duplist = list.get(list.size()-1);
        for(int i=0;i<=numRows-1;i++){
            if(i==0||i==numRows-1)
                inlist.add(1);
            else
                inlist.add(duplist.get(i-1)+duplist.get(i));
        }
        list.add(inlist);
        }
        return list;
    }
}

Java Solution(Iteration/DP)

public class Solution {
    public List<List<Integer>> generate(int numRows) {
        List<List<Integer>> res = new ArrayList<List<Integer>>();
        List<Integer> row, pre = null;
        for (int i = 0; i < numRows; ++i) {
            row = new ArrayList<Integer>();
            for (int j = 0; j <= i; ++j)
                if (j == 0 || j == i)
                    row.add(1);
                else
                    row.add(pre.get(j - 1) + pre.get(j));
            pre = row;
            res.add(row);
        }
        return res;
    }
}