卖萌的弱渣

I am stupid, I am hungry.

Pascal’s Triangle

Given numRows, generate the first numRows of Pascal’s triangle.

For example, given numRows = 5, Return

1
2
3
4
5
6
7
[
     [1],
    [1,1],
   [1,2,1],
  [1,3,3,1],
 [1,4,6,4,1]
]

Solution

  • Java
(Pascal-Triangle.java) download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
public class Solution {
    public List<List<Integer>> generate(int numRows) {
        List<List<Integer>> ret = new ArrayList<List<Integer>>();
        if (numRows<=0)
            return ret;
        for (int i=0;i<numRows;i++){
            List<Integer> row = new ArrayList<Integer>();
            for(int j=0;j<i+1;j++){
                if (j==0 || j==i)
                    row.add(1);
                else
                    row.add(ret.get(i-1).get(j-1) + ret.get(i-1).get(j));
            }
            ret.add(row);
        }
       return ret;
    }
}
  • Python
(Pascal-Triangle.py) download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
class Solution(object):
    def generate(self, numRows):
        """
        :type numRows: int
        :rtype: List[List[int]]
        """
        ret = []
        if numRows < 1:
            return ret
        ret.append([1])
        if numRows == 1:
            return ret

        for i in range(1,numRows):
            tmp = [1]
            for j in range(1, i):
                tmp.append(ret[i-1][j] + ret[i-1][j-1])
            tmp.append(1)
            ret.append(tmp[:])
        return ret