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++版代码:
class Solution { public: vector<vector<int> > generate(int numRows){ if(numRows==0) return vector<vector<int> > (0); vector<vector<int> > ivec; int i=0,j=0; for(i=0;i<numRows;i++){ vector<int> vec; for(j=0;j<i+1;j++){ if(j==0||j==i) vec.push_back(1); else vec.push_back(ivec[i-1][j-1]+ivec[i-1][j]); } ivec.push_back(vec); } return ivec; } };
Java版代码:
public class Solution { private ArrayList<ArrayList<Integer>> res=new ArrayList<ArrayList<Integer>>(); public ArrayList<ArrayList<Integer>> generate(int numRows) { if(numRows==0) return res; int i=0, j=0; for(i=0;i<numRows;i++) { ArrayList<Integer> vec=new ArrayList<Integer>(); for(j=0; j<i+1; j++){ if(j==0 || i==j) vec.add(1); else vec.add(res.get(i-1).get(j-1)+res.get(i-1).get(j)); } res.add(vec); } return res; } }