打印杨辉三角/帕斯卡三角问题

问题描述

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]
]

解题思路

杨辉三角形的规律是,每一行的每一个值,等于其上一行中该值肩膀上抗的两个值,也就是C(n+1,i)=C(n,i)+C(n,i-1)

代码示例

class Solution {
public:
    vector<vector<int> > generate(int numRows) {
        vector<vector<int>> res;
        for (int i = 0; i < numRows; i++) {
            vector<int> temp(i + 1, 1);//初始化该行值为全1
            for (int j = 1; j < i; j++) {
                temp[j] = res[i - 1][j - 1] + res[i - 1][j];
            }
            res.push_back(temp);
        }
        return res;
    }
};

问题描述

Given an index k, return the k th 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?

解题思路

要求额外空间复杂度为O(k),则不能采用上题方法,为保证下一行在更新时,前面的值不会被覆盖,则更改更新顺序,每次从最后面开始更新,这样不会提前覆盖掉前面的值。举个例子,

[ [1],

[1,1],

[1,2,1],

[1,3,3,1],

[1,4,6,4,1] ]

计算第五行时,从计算倒数第一个4开始,4 = 3 + 1,覆盖掉最后的1,但没有变3,继续计算6 = 3 + 3,覆盖掉3,但没有变前一个3,依次覆盖下去,该行即可更新完毕,且额外空间为O(k)

代码示例

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值