Pascal's Triangle II

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?


既然要求空间复杂度为O(K),就不能使用二位数组把整个杨辉三角表示出来。而是使用一维数组,只用来表示杨辉三角中的某一行,这样的话空间复杂度为0(K),而时间复杂度就大大增大了。

先建立一个只有一个元素1的的向量,在此基础上,通过循环相加,逐渐增大向量的大小。

注意:在循环相加的过程中,要保留前一个元素的值

C++代码如下:

class Solution {
public:
    vector<int> getRow(int rowIndex) {
        vector<int> pascal(1,1);
        while(rowIndex > 0) {
            pascal.push_back(0);
            int pre = 0;//初始化pre数值为0
            for(auto it = pascal.begin(); it != pascal.end(); it++) {
                int temp = *it;
                *it = *it + pre;
                pre = temp;
            }
            rowIndex--;
        }
        return pascal;
    }
};

其中,for循环里面auto it = pascal.begin()中的auto为C++11的新特性,这里的功能是自动类型推断。

auto的详细介绍见 【C++11】新特性——auto的使用


java代码如下:

class Solution {
    public List<Integer> getRow(int rowIndex) {
        List<Integer> pascal = new ArrayList<>();
        pascal.add(1);
        while(rowIndex > 0) {
            pascal.add(0);
            int pre = 0;
            for(int i = 0; i < pascal.size(); i++) {
                int temp = pascal.get(i);
                pascal.set(i,pascal.get(i) + pre);
                pre = temp;
            }
            rowIndex--;
        }
        return pascal;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值