Total Accepted: 51715
Total Submissions: 175265
Difficulty: Easy
Given an index k, return the kth row of the Pascal's triangle.
For example, given k = 3,
Return [1,3,3,1]
.
Note:
Could you optimize your algorithm to use only O(k) extra space?
Show Similar Problems
Have you met this question in a real interview?
该题目与上一题不同在于只需返回一行的数据。我记得高中时期有发现杨辉三角每一行值的方法,但是忘了,所以就采用上一题相似的方法,不过,上一题是把每一行都保存下来,这次不同,只保留前一行的值,便于下一行计算。
class Solution {
public:
vector<int> getRow(int numRows)
{
vector<int> temp;
vector<vector<int>> result;
if (numRows < 0)
return{};
temp.push_back(1);
int m = 0;
result.push_back(temp);
temp.clear();
for (int i = 2; i < numRows+2; i++)
{
temp.push_back(1);
for (int j = 2; j < i; j++)
{
m = result[0][j - 2] + result[0][j - 1];
temp.push_back(m);
}
temp.push_back(1);
result.clear();
result.push_back(temp);
temp.clear();
}
return result[0];
}
};
public:
vector<int> getRow(int numRows)
{
vector<int> temp;
vector<vector<int>> result;
if (numRows < 0)
return{};
temp.push_back(1);
int m = 0;
result.push_back(temp);
temp.clear();
for (int i = 2; i < numRows+2; i++)
{
temp.push_back(1);
for (int j = 2; j < i; j++)
{
m = result[0][j - 2] + result[0][j - 1];
temp.push_back(m);
}
temp.push_back(1);
result.clear();
result.push_back(temp);
temp.clear();
}
return result[0];
}
};