力扣题-10.2
力扣题1:118. 杨辉三角
解题思想:使用temp保存前一行的结果,temp1保存当前行结果,遍历数组即可,需要考虑第一个和最后一个是1
class Solution(object):
def generate(self, numRows):
"""
:type numRows: int
:rtype: List[List[int]]
"""
if numRows==1:
return [[1]]
else:
result =[[1]]
temp = [1]
for i in range(1,numRows):
temp1 = []
for j in range(len(temp)):
if j==0:
temp1.append(1)
else:
temp1.append(temp[j-1]+temp[j])
temp1.append(1)
result.append(temp1)
temp=temp1
return result
class Solution {
public:
vector<vector<int>> generate(int numRows) {
if(numRows == 1){
return {{1}};
}
else{
std::vector<std::vector<int>> result;
result.push_back({1});
std::vector<int> temp = {1};
for (int i = 1; i < numRows; i++){
std::vector<int> temp1;
for (int j = 0; j < temp.size(); j++) {
if (j == 0){
temp1.push_back(1);
}
else{
temp1.push_back(temp[j - 1] + temp[j]);
}
}
temp1.push_back(1);
result.push_back(temp1);
temp = temp1;
}
return result;
}
}
};
力扣题2:119. 杨辉三角 II
解题思想:
1.与上一题一样,最后return的结果变成当前行即可
2.官方题解:线性递推的方式得到同一行的相邻组合数关系
class Solution(object):
def getRow(self, rowIndex):
"""
:type rowIndex: int
:rtype: List[int]
"""
if rowIndex==0:
return [1]
else:
result =[[1]]
temp = [1]
for i in range(0,rowIndex):
temp1 = []
for j in range(len(temp)):
if j==0:
temp1.append(1)
else:
temp1.append(temp[j-1]+temp[j])
temp1.append(1)
result.append(temp1)
temp=temp1
return temp
class Solution {
public:
vector<int> getRow(int rowIndex) {
if(rowIndex == 0){
return {1};
}
else{
std::vector<std::vector<int>> result;
result.push_back({1});
std::vector<int> temp = {1};
for (int i = 0; i < rowIndex; i++){
std::vector<int> temp1;
for (int j = 0; j < temp.size(); j++) {
if (j == 0){
temp1.push_back(1);
}
else{
temp1.push_back(temp[j - 1] + temp[j]);
}
}
temp1.push_back(1);
result.push_back(temp1);
temp = temp1;
}
return temp;
}
}
};
class Solution(object):
def getRow(self, rowIndex):
"""
:type rowIndex: int
:rtype: List[int]
"""
row = [0] * (rowIndex + 1)
row[0] = 1
for i in range(1, rowIndex + 1):
row[i] = row[i - 1] * (rowIndex - i + 1) // i
return row
class Solution {
public:
vector<int> getRow(int rowIndex) {
vector<int> row(rowIndex + 1);
row[0] = 1;
for (int i = 1; i <= rowIndex; ++i) {
row[i] = 1LL * row[i - 1] * (rowIndex - i + 1) / i;
}
return row;
}
};