Pascal's Triangle II
Given an indexk, return thekthrow of the Pascal's triangle.
For example, givenk= 3,
Return[1,3,3,1]
.
Note:
Could you optimize your algorithm to use onlyO(k) extra space?
Tips:
注意杨辉三角的定义。然后注意i和j的开始以及结束。每次巧妙地在第一位插入1并且在res.size() - 1停止保证最后一个也是1。
Complexity: O(n^2)
Code:
public class Solution {
public List<Integer> getRow(int rowIndex) {
List<Integer> res = new ArrayList<>();
if (rowIndex < 0) return res;
for (int i = 0; i < rowIndex + 1; i++) {
res.add(0, 1);
for (int j = 1; j < res.size() - 1; j++) {
res.set(j, res.get(j) + res.get(j + 1));
}
}
return res;
}
}