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?
既然要求空间复杂度为O(K),就不能使用二位数组把整个杨辉三角表示出来。而是使用一维数组,只用来表示杨辉三角中的某一行,这样的话空间复杂度为0(K),而时间复杂度就大大增大了。
先建立一个只有一个元素1的的向量,在此基础上,通过循环相加,逐渐增大向量的大小。
注意:在循环相加的过程中,要保留前一个元素的值
C++代码如下:
class Solution {
public:
vector<int> getRow(int rowIndex) {
vector<int> pascal(1,1);
while(rowIndex > 0) {
pascal.push_back(0);
int pre = 0;//初始化pre数值为0
for(auto it = pascal.begin(); it != pascal.end(); it++) {
int temp = *it;
*it = *it + pre;
pre = temp;
}
rowIndex--;
}
return pascal;
}
};
其中,for循环里面auto it = pascal.begin()中的auto为C++11的新特性,这里的功能是自动类型推断。
auto的详细介绍见 【C++11】新特性——auto的使用
java代码如下:
class Solution {
public List<Integer> getRow(int rowIndex) {
List<Integer> pascal = new ArrayList<>();
pascal.add(1);
while(rowIndex > 0) {
pascal.add(0);
int pre = 0;
for(int i = 0; i < pascal.size(); i++) {
int temp = pascal.get(i);
pascal.set(i,pascal.get(i) + pre);
pre = temp;
}
rowIndex--;
}
return pascal;
}
}