题目:
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?
思路:
O(k)的空间复杂度的限制就是不允许像118那样做,一直纠结在118的方法中,所以看了discuss才知道怎么做。
创建大小为k的数组,外循环用于创建第i行的结果,内循环用于从i-1行结果构造第i行结果,方法是从末端利用a[j] = a[j] + a[j-1]
代码:
public class Solution {
public List<Integer> getRow(int rowIndex) {
List<Integer> result = new ArrayList<Integer>(rowIndex+1);
//处理特殊情况
if(rowIndex < 0){return result;}
result.add(1);
if(rowIndex == 0){
return result;
}
//i表示层数,表示每层的数字
for(int i = 1; i <= rowIndex; i++){
result.add(1);
//直接从第i-1行修改从后向前遍历,除了前后的两个1外,其他的值为第j个值+第j-1个值
for(int j = i-1; j >= 1; j--){
int t = result.get(j)+result.get(j-1);
result.set(j,t);
}
}
return result;
}
}
在看了discuss之后还有一种数学的方法,利用一个公式,我没有写,将discuss中的内容copy过来。。。
原文:https://leetcode.com/discuss/77693/my-clean-o-k-java-solution
Based on rules:
row k of Pascal's Triangle:
[C(k,0), C(k,1), ..., C(k, k-1), C(k, k)]
and
C[k,i] = C[k,i-1]*(k-i+1)/i
public class Solution {
public List<Integer> getRow(int rowIndex) {
Integer[] rowList = new Integer[rowIndex+1];
rowList[0] = 1;
for(int i=1; i<rowList.length;i++) {
rowList[i] = (int)((long)rowList[i-1]*(rowIndex-(i-1))/(i));
}
return Arrays.asList(rowList);
}
}