119. Pascal's Triangle II(python+cpp)

题目:

Given a non-negative index k where k ≤ 33, return the kth index row of the Pascal’s triangle.
Note that the row index starts from 0.
在这里插入图片描述

In Pascal’s triangle, each number is the sum of the two numbers directly above it.
Example:

Input: 3 
Output: [1,3,3,1] 

Follow up:
Could you optimize your algorithm to use only O(k) extra space.

解释:
杨辉三角系列的第二题。可以直接像I一样保存每一行的结果,然后返回最后一行即可。
python代码:

class Solution:
    def getRow(self, rowIndex):
        """
        :type rowIndex: int
        :rtype: List[int]
        """
        result=[]
        for numRow in range(rowIndex+1):
            tmp=[0]*(numRow+1)
            tmp[0]=1
            tmp[-1]=1
            for i in range (1,len(tmp)-1):
                tmp[i]=result[numRow-1][i-1]+result[numRow-1][i]
            result.append(tmp)
        return result[-1];

c++代码:

class Solution {
public:
    vector<int> getRow(int rowIndex) {
        vector<vector<int>> result;
        for (int i=0;i<rowIndex+1;i++)
        {
            vector<int> tmp(i+1,0);
            tmp[0]=1;
            tmp[i]=1;
            for (int j=1;j<i;j++)
            {
                tmp[j]=result[i-1][j-1]+result[i-1][j];
            }
            result.push_back(tmp);
        }
        return result[rowIndex];
    }
};

还要求用O(k)的空间复杂度完成,也就是说不能每一次都保存所有的结果。要注意到杨辉三角对称的性质。
python代码(注意是逆序,然后是向下取整哦):

class Solution:
    def getRow(self, rowIndex):
        """
        :type rowIndex: int
        :rtype: List[int]
        """
        result=[1]
        if rowIndex==0:
            return result
        result.append(1)
        if rowIndex==1:
            return result
        for i in range(2,rowIndex+1):
            result.append(1)
            n=len(result)
            #逆序的原因是防止前面变了影响后面
            for j in range(n-2,0,-1):
                if (j>=n//2):
                    result[j]=result[j]+result[j-1]
                else:
                    result[j]=result[n-1-j]
        return result;

c++代码:

class Solution {
public:
    vector<int> getRow(int rowIndex) {
        vector<int>result={1};
        if (rowIndex==0)
            return result;
        result.push_back(1);
        if(rowIndex==1)
            return result;
        for(int i=2;i<=rowIndex;i++)
        {
            result.push_back(1);
            int n =result.size();
            for (int j=n-2;j>0;j--)
            {
                if(j>=n/2)
                    result[j]+=result[j-1];
                else
                    result[j]=result[n-1-j];
            }
        }
        return result;
    }
};

总结:
记住O(k)时间复杂度的写法。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值