一,第118题
题干:
Given numRows, generate the first numRows of Pascal’s triangle.
For example, given numRows = 5,
Return
[
[1],
[1,1],
[1,2,1],
[1,3,3,1],
[1,4,6,4,1]
]
题目就是中国的杨辉三角。
采用递归解决,为了节省时间与空间,在递归的过程中直接将结果保存进去,这样,只需要彻底递归一次,就得到结果。
效率还行,时间为4ms;
class Solution {
public:
vector<vector<int> > re;//保存最终结果
vector<int> tmp;//保存中间结果,即每一层的结果
void Pascal_triangle(int i){
if(i < 1)//用于判断边界,去除不符合要求的输入
return;
else if(i == 1)//最底层的处理
{
tmp.push_back(i);
re.push_back(tmp);
return;
}
else
{
Pascal_triangle( i-1);//递归处理
vector<int> cur=tmp;
tmp.clear();
for(int j=1; j <= i; j++)
{
if(1==j || j==i)//每一行的开头和结尾都是1
{
tmp.push_back(1);
}
else//介于开头和结尾之间的,用杨辉三角思想
{
tmp.push_back(cur[j-2]+cur[j-1]);//注意下标,防止出界
}
}
re.push_back(tmp);
return;
}
}
vector<vector<int>> generate(int numRows) {
re.clear();
Pascal_triangle(numRows);
return re;
}
};
二,第119题
题干:
Given an index k, return the kth row of the Pascal’s triangle.
For example, given k = 3,
Return [1,3,3,1].
这题其实就是上一题的一个化简,最终结果只需要返回最后一次的结果即可。
同样采用递归的办法,效率与上一题差不多。
时间同样为4ms;
class Solution {
public:
vector<int> re;//保存结果
void Pascal_triangle_Row(int i)
{
if(i < 1)//排除错误输入
return;
else if(i == 1)//基本情况
{
re.clear();
re.push_back(i);
}
else
{
Pascal_triangle_Row( i-1 );//递归调用
vector<int> tmp=re;
re.clear();
for(int j=1; j <= i; j++)
{
if(j==1 || j==i)//每一行的开头和结尾为1
{
re.push_back(1);
}
else
{
re.push_back(tmp[j-2]+tmp[j-1]);//注意下标,防止出界
}
}
return;
}
}
vector<int> getRow(int rowIndex) {
Pascal_triangle_Row( rowIndex+1 );//注意参数+1
return re;
}
};
本文详细介绍了如何使用递归方法解决杨辉三角问题,包括两个实例:生成指定行数的杨辉三角和获取特定行的结果。通过递归过程直接保存结果,提高了效率。
5212

被折叠的 条评论
为什么被折叠?



