LeetCode | Pascal's Triangle II

题目:

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?

思路:

类似
http://blog.csdn.net/lanxu_yy/article/details/11881907,但是为了合理利用空间,我们只记录上一层的结果。也可以用递归的方法来完成。

代码:

非递归方法:

class Solution {
public:
    vector<int> getRow(int rowIndex) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
        if(rowIndex == 0)
        {
            vector<int> r;
            r.push_back(1);
            
            return r;
        }
        else if(rowIndex == 1)
        {
            vector<int>* r = new vector<int>();
            r->push_back(1);
            r->push_back(1);
            
            return *r;
        }
        else
        {
            vector<int>* temp = new vector<int>();
            vector<int>* r;
            temp->push_back(1);
            temp->push_back(1);
            
            for(int i = 2; i <= rowIndex; i++)
            {
                r = new vector<int>();
                r->push_back(1);
                for(int j = 1; j < i; j++)
                {
                    r->push_back(temp->at(j-1) + temp->at(j));
                }
                r->push_back(1);
                delete temp;
                temp = r;
            }
            
            return *r;
        }
    }
};

递归方法:

class Solution {
public:
    vector<int> getRow(int rowIndex) {
        vector<int> tmp;
        if(rowIndex == 0){
            tmp.push_back(1);
        }
        else if(rowIndex == 1){
            tmp.push_back(1);
            tmp.push_back(1);
        }
        else{
            vector<int> parent = getRow(rowIndex - 1);
        
            for(int i = 0; i <= rowIndex; i++){
                if(i == 0 || i == rowIndex){
                    tmp.push_back(1);
                }
                else{
                    tmp.push_back(parent[i - 1] + parent[i]);
                }
            }
        }
        return tmp;
    }
};
    原文作者:Allanxl
    原文地址: https://blog.csdn.net/lanxu_yy/article/details/11882083
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞