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] ]
关键记录上一层的结点即pre,每一层的第i个位置,等于上一层第i-1与第i个位置之和。
public List<List<Integer>> generate(int numRows) {
List<List<Integer>> result = new ArrayList<>();
if (numRows <= 0)
return result;
// 指向上一个三角形
List<Integer> pre = new ArrayList<>();
pre.add(1);
result.add(pre);
// i代表层数,从1开始
for (int i = 2; i <= numRows; i++) {
List<Integer> cur = new ArrayList<Integer>();
// first
cur.add(1);
for (int j = 0; j < pre.size() - 1; j++) {
// middle
cur.add(pre.get(j) + pre.get(j + 1));
}
// last
cur.add(1);
result.add(cur);
pre = cur;
}
return result;
}
119. Pascal’s Triangle II
Given an index k, return the kth row of the Pascal’s triangle.
For example, given k = 3,
Return [1,3,3,1]
.
Note:
Could you optimize your algorithm to use only O(k) extra space?
获取第k行的杨辉三角,k从0开始
public List<Integer> getRow(int rowIndex) {
List<Integer> res = new ArrayList<Integer>();
if (rowIndex < 0)
return res;
res.add(1);
for (int i = 1; i <= rowIndex; i++) {
// 从后往前覆盖
for (int j = res.size() - 2; j >= 0; j--) {
res.set(j + 1, res.get(j) + res.get(j + 1));
}
res.add(1);
}
return res;
}