这个题关键是注意第二个循环,必须倒序的修改杨辉三角的值,不能顺序的改。
C++
解法
时间复杂度O(n^2),空间复杂度O(k) 耗时0ms
class Solution {
public:
vector<int> getRow(int rowIndex) {
vector<int> array;
for (int i = 0; i <= rowIndex; i++) {
for (int j = i - 1; j > 0; j--) {
array[j] = array[j] + array[j-1];
}
array.push_back(1);
}
return array;
}
};
python
解法1
思路和上面一样,简单的迁移到python,但是耗时52ms
class Solution(object):
def getRow(self, rowIndex):
"""
:type rowIndex: int
:rtype: List[int]
"""
result = []
for i in range(0,rowIndex+1) :
for j in range(i-1,0,-1) :
result[j] = result[j-1] + result[j]
result.append(1)
return result