leetcode-118&119 Pascal's Triangle I & II

本文详细介绍了如何使用递归方法解决杨辉三角问题,包括两个实例:生成指定行数的杨辉三角和获取特定行的结果。通过递归过程直接保存结果,提高了效率。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一,第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;
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值