问题描述
题目看链接:https://leetcode.com/problems/pascals-triangle-ii/
解决思路
这题除了题目和118有略微不同,只需要返回最后一行,还有就是需要在O(n)空间完成,虽然118虽然改一下就能出结果,但那个是O(n^2)。其实杨辉三角有一个公式,即第n行的m个数可表示为 C(n-1,m-1).这样就很简单了,算出第n行第一个数,然后遍历该行就可以了(该行元素个数和行数相等)
代码
package leetcode;
import java.util.ArrayList;
import java.util.List;
public class PascalsTriangleII {
public List<Integer> getRow(int rowIndex) {
List<Integer> res = new ArrayList<>();
long num = 1;
for (int i = 0; i <= rowIndex; i++) {
res.add((int)num);
num = num * (rowIndex - i) / (i + 1);
}
return res;
}
}