leetcode 119:Pascal's Triangle II

27 篇文章 0 订阅
2 篇文章 0 订阅

问题描述:

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?

思路:

这道题和版本一 Pascal’s Triangle 的题目几乎一样,所以改一下返回值就行了,这就有了 code I。
但题目有进阶 O(k) 的要求,于是可以想着只保留上一个数组即可,便是 code II。

代码:

//  code I
class Solution { 
public:
    vector<int> getRow(int rowIndex) {
        int numRows = rowIndex+1;    // compare to the Pascal's Triangle I,only the index and return value are different
        vector<vector<int>> result;
        vector<int> temp;
        if (numRows == 0) return temp;

        temp.push_back(1);
        result.push_back(temp);
        if (numRows == 1) return temp;

        temp.push_back(1);
        result.push_back(temp);
        if (numRows == 2) return result.back();

        for (int i = 3; i <= numRows; i++)    
        {
            vector<int> layer;
            layer.push_back(1);
            vector<int> former = result[i - 2];     //found the corresponding array
            for (int j = 0; j < former.size() - 1; j++)
            {
                layer.push_back(former[j] + former[j + 1]);
            }
            layer.push_back(1);

            result.push_back(layer);
        }
        return result.back();
    }
};
//code II
class Solution {
public:
    vector<int> getRow(int rowIndex) {
        vector<int> result;
        int numRows = rowIndex+1;

        if (numRows == 0) return result;

        result.push_back(1);
        if (numRows == 1) return result;

        result.push_back(1);
        if (numRows == 2) return result;

        for (int i = 3; i <= numRows; i++)    
        {
            vector<int> pre_result;
            pre_result.swap(result);  //swap to the easy-operated position
            result.push_back(1);

            for (int j = 0; j < i - 2; j++)
            {
                result.push_back(pre_result[j]+pre_result[j+1]);
            }

        }
        result.push_back(1);
        return result;
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值