LeetCode 119. Pascal’s Triangle II
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?
解析:
此题目是在LeetCode 118. Pascal’s Triangle上做个升级,直接根据下标获取对应行数的数组内容,并且要求限制空间复杂度。
依据上个题目中杨辉三角的性质,当前层的元素都是上一层相邻元素之和,采用两层循环,当前循环是在上一层循环结果之上进行处理,在循环内部,从后往前倒叙来处理每一行元素。
具体代码如下:
[cc lang=”C++”]
class Solution {
public:
vector
vector
result[0] = 1;
for(int i=1; i < rowIndex+1; i++)//依次遍历每一行
{
for(int j=i; j >=1; j–)//每一行内部倒序进行扩展
result[j] += result[j-1];//当前位置元素等于上一层对应位置的两个元素之和
}
return result;
}
};
[/cc]
运行结果:
