题目描述:
Given a non-negative index k where k ≤ 33, return the kth index row of the Pascal's triangle.
Note that the row index starts from 0.
In Pascal's triangle, each number is the sum of the two numbers directly above it.
Example:
Input: 3 Output: [1,3,3,1]
Follow up:
Could you optimize your algorithm to use only O(k) extra space?
中文理解:杨辉三角,返回下标为k的层,第一层下标为0,依次类推。
解题思路:从上面动图可以看出来,杨辉三角的每一层仅仅与上一层有关,故仅仅需要保存两层的数据即可。或者可以采用Cn(m)组合数的方法来得到每一个值,仅仅需要O(k)的空间,这次解法采用的是第一种解法。
代码(java):
class Solution {
public List<Integer> getRow(int rowIndex) {
List<Integer> res=new ArrayList<Integer>();
if(rowIndex==0){
res.add(1);
}
else if(rowIndex==1){
res.add(1);
res.add(1);
}
else{
List<Integer> before=new ArrayList<Integer>();
before.add(1);
before.add(1);
for(int i=2;i<=rowIndex;i++){
for(int j=0;j<=i;j++){
if(j==0 || j==i){
res.add(1);
}
else{
res.add(before.get(j-1)+before.get(j));
}
}
if(i<rowIndex){
before=res;
res=new ArrayList<Integer>();
}
}
}
return res;
}
}