LintCode 1354: Pascal's Triangle II

LintCode-Logo
Home
Algorithms
AI
CATnew
VIP
Language
avatarroufoo
Back
1354. Pascal’s Triangle II
Description
Given a non-negative index k where k ≤ 33, return the kth index row of the Pascal’s triangle.

1.Note that the row index starts from 0.
2.In Pascal’s triangle, each number is the sum of the two numbers directly above it.

Have you met this question in a real interview?
Example
Example:

Input: 3
Output: [1,3,3,1]
Challenge
Could you optimize your algorithm to use only O(k) extra space?

Related Problems
Amazon

3 - Hard

67%
DifficultyEasy
Total Accepted518
Total Submitted810
Accepted Rate63%
Show Tags
Company
Leaderboard - C++

afrozan
7ms

OrionPax
7ms

emmaz
8ms

ziken.neo
8ms

chong58
50ms
Note
迭代计算每行的值,由于更新的过程中会覆盖掉一些后续还要使用的元素,所以用tmp0和tmp1来保存下一次需要相加的两个值。
victoryong
Created at 4 days ago
对任意的n>0有   f(1, n)=1,(n>0)   f(n, n)=1,(n>2)   f(i,j) = f(i-1, j-1)+f(i, j-1),i>2,j>2,   求第k行。 list用法,set, add
sun533
Created at 7 months ago
Discuss
No topic

  1. Pascal’s Triangle II
    Given a non-negative index k where k ≤ 33, return the kth index row of the Pascal’s triangle.

Example
Example:

Input: 3
Output: [1,3,3,1]
Challenge
Could you optimize your algorithm to use only O(k) extra space?

Notice
1.Note that the row index starts from 0.
2.In Pascal’s triangle, each number is the sum of the two numbers directly above it.

代码如下:


class Solution {
public:
    /**
     * @param rowIndex: a non-negative index
     * @return: the kth index row of the Pascal's triangle
     */
    vector<int> getRow(int rowIndex) {
        vector<int> result;
        if (rowIndex == 0) {
            result = {1};
            return result;
        }
        
        if (rowIndex == 1) {
            result = {1,1};
            return result;
        }
        
        vector<int> formerResult = {1, 1};
        result.push_back(1);
        for (int i = 2; i < rowIndex + 1; ++i) {

            int len = formerResult.size() - 1;
            for (int j = 0; j < len; ++j) {
                result.push_back(formerResult[j] + formerResult[j + 1]);    
            }
            result.push_back(1);
            formerResult = result;
            if (i < rowIndex) result = {1};
        }

        return result;
    }
};

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值