LeetCode刷题笔记--119. Pascal's Triangle II

119. Pascal's Triangle II

Easy

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?

class Solution {
public:
    vector<int> getRow(int rowIndex) {
        vector<int> ans;
        ans.clear();
        vector<int> t;
        t.clear();
        ans.push_back(1);
        if(rowIndex==0)return ans;
        ans.push_back(1);
        if(rowIndex==1)return ans;
        t=ans;
        for(int i=2;i<=rowIndex;i++)
        {
            ans.clear();
            ans.push_back(1);
            int p=i+1-2;
            int k=0;
            while(p>=1)
            {
                ans.push_back(t[k]+t[k+1]);
                p--;
                k++;
            }
            ans.push_back(1);
            t=ans;
        }
        return ans;
    }
};

猜你喜欢

转载自blog.csdn.net/vivian0239/article/details/88256070