题目
Given a non-negative index k where k ≤ 33, return the kth index row of the Pascal’s triangle.
Note that the row index starts from 0.
Example:
Input: 3
Output: [1,3,3,1]
我的想法
have no idea…
解答
外轮循环代表着第i行的计算,进入下一行时在最后append 1,但数值还是上一行的,所以可以直接用res.get(j-1) + res.get(j)
来更新数值。需注意,内循环必须由后往前
public List<Integer> getRow(int rowIndex) {
List<Integer> res = new ArrayList<>();
for(int i = 0; i <= rowIndex; i++) {
res.add(1);
for(int j = i-1; j > 0; j--) {//必须由后向前,否则加数改变
res.set(j, res.get(j-1) + res.get(j));
}
}
return res;
}