Pascal's Triangle I II
3478 ワード
よく考えて、細部を手配するのは難しくない.
II
public class Solution {
public ArrayList<ArrayList<Integer>> generate(int numRows) {
ArrayList<ArrayList<Integer>> res = new ArrayList<ArrayList<Integer>>();
if(numRows<=0) return res;
ArrayList<Integer> tmp = new ArrayList<Integer>();
tmp.add(1);
res.add(tmp);
for(int i=1;i<numRows;i++){ // current row to be added
ArrayList<Integer> r = new ArrayList<Integer>();
r.add(1);
ArrayList<Integer> t = res.get(i-1);
for(int j=1;j<i;j++){
r.add(t.get(j)+t.get(j-1));
}
r.add(1);
res.add(r);
}
return res;
}
}
II
public class Solution {
public ArrayList<Integer> getRow(int rowIndex) {
ArrayList<Integer> res = new ArrayList<Integer>();
if(rowIndex<0) return res;
res.add(1);
for(int i=1;i<=rowIndex;i++){
ArrayList<Integer> cur = new ArrayList<Integer>();
cur.add(1);
for(int j=1;j<i;j++){
cur.add(res.get(j)+res.get(j-1));
}
cur.add(1);
res =cur;
}
return res;
}
}