题目地址:https://leetcode.com/problems/pascals-triangle-ii/
Given an index k, return the *k*th 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?
本题目与杨辉三角的打印相关,是 Pascal’s Triangle 的简化版本,想要打印杨辉三角的第n行数据,那么只要直到第n-1行的数据是啥情况就可以了。所以在计算的过程中,每次迭代只保留好上一行的信息就行了,再往前的信息就没啥用了。
代码实现如下:
public class PascalsTriangleII {
public List<Integer> getRow(int rowIndex) {
List<Integer> curList = new ArrayList<>();
if (rowIndex < 0) {
curList.add(1);
return curList;
}
if (rowIndex == 0)
return curList;
for (int i = 0; i <= rowIndex; i++) {
List<Integer> preList = new ArrayList<Integer>(curList);
curList.clear();
if (i == 0) {
curList.add(1);
continue;
}
if (i == 1) {
curList.add(1);
curList.add(1);
continue;
}
for (int j = 0; j <= preList.size(); j++) {
if (j == 0 || j == preList.size())
curList.add(1);
else
curList.add(preList.get(j-1) + preList.get(j));
}
preList = curList;
}
return curList;
}
public static void main(String[] args) {
PascalsTriangleII pascalsTriangleII = new PascalsTriangleII();
System.out.println(pascalsTriangleII.getRow(4));
}
}