您的位置:首页 > 其它

LeetCode | Pascal's Triangle II

2013-09-21 22:32 260 查看

题目:

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?

思路:

类似/article/1382603.html,但是为了合理利用空间,我们只记录上一层的结果。也可以用递归的方法来完成。

代码:

非递归方法:
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;
    }
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: