Given an index k, return the kth row of the Pascal's triangle.
For example, given k = 3,
Return [1,3,3,1]
.
要求输出第k行杨辉三角的值,只能使用额外的O(k)大小的空间。
public class Solution {
public List<Integer> getRow(int rowIndex) {
List<Integer> r = new ArrayList<Integer>();
int[] temp = new int[rowIndex+1];
temp[0] = 1;
for(int k = 1; k <= rowIndex; k++){
for(int i = k; i >= 0; i--){
if(i == 0 || i == k){
temp[i] =1;
continue;
}
temp[i] = temp[i] + temp[i-1];
}
}
for(int i = 0; i < rowIndex+1; i++){
r.add(temp[i]);
}
return r;
}
}
依旧是使用杨辉三角的性质,第i 行的第j 个元素的值等于第 i-1 行的第j 个元素与第j-1 个元素的和。但是这里需要将i 从k 递减至0; 否则 temp[i] = temp[i] + temp[i-1]的值将影响下次的temp[i+1]的值得计算。