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] ]
C++(3ms):
1 class Solution { 2 public: 3 vector<vector<int>> generate(int numRows) { 4 vector<vector<int>> res(numRows) ; 5 if (numRows < 1) 6 return res ; 7 for (int i = 0 ; i < numRows ; i++){ 8 res[i].resize(i + 1); 9 res[i][0] = res[i][i] = 1 ; 10 for (int j = 1 ; j < i ; j++){ 11 res[i][j] = res[i-1][j-1]+res[i-1][j] ; 12
13 } 14 } 15 return res ; 16 } 17 };
java(1ms):
1 class Solution { 2 public List<List<Integer>> generate(int numRows) { 3 List<List<Integer>> res = new ArrayList<List<Integer>>() ; 4 5 if (numRows < 1) 6 return res ; 7 for(int i = 0 ; i < numRows ; i++){ 8 ArrayList<Integer> row = new ArrayList<Integer>() ; 9 for(int j = 0 ; j < i + 1; j++){ 10 if (j == 0 || j == i) 11 row.add(1) ; 12 else 13 row.add(res.get(i-1).get(j-1) + res.get(i-1).get(j)) ; 14 } 15 res.add(row) ; 16 } 17 return res ; 18 } 19 }