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?
原题链接:https://oj.leetcode.com/problems/pascals-triangle-ii/
题目:给定一个索引k,返回帕斯卡三角形的第k行。
思路 : 此题可以用上一题中的方法来解,直接就是通项公式,与k行之前的行没有关系。
也可以一次分配结果所需大小的list,每次计算一行,并将结果置于合适的位置,下一行采用上一行的结果进行计算。
public static List<Integer> getRow(int rowIndex) {
if (rowIndex < 0)
return null;
List<Integer> result = new ArrayList<Integer>(rowIndex + 1);
result.add(1);
for (int i = 1; i <= rowIndex; i++) {
int temp1 = 1;
for (int j = 1; j < i; j++) {
int temp2 = result.get(j);
result.set(j, temp1 + temp2);
temp1 = temp2;
}
result.add(1);
}
return result;
}
reference : http://www.darrensunny.me/leetcode-pascals-triangle-ii/