LEETCODE--Pascal's Triangle II

来源:互联网 发布:手机简单制图软件 编辑:程序博客网 时间:2024/06/09 19:44

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?

Subscribe to see which companies asked this question
方法一:
从后往前进行加法赋值;

class Solution {public:    vector<int> getRow(int rowIndex) {        vector<int> A;         A.push_back(1);        if(rowIndex == 0)            return A;        A.push_back(1);        if(rowIndex == 1)            return A;        for(int x = 2; x <= rowIndex; x++){           A.push_back(0);        }        for(int i = 2; i <= rowIndex; i++){            A[i] = 1;            for(int j = i-1; j > 0; j--){                A[j] = A[j] + A[j-1];                }            A[0] = 1;        }        return A;    }};

方法二:

class Solution {public:    vector<int> getRow(int rowIndex) {        vector<vector<int>> finsh;        vector<int> last;        vector<int> add;        finsh.push_back(add);        finsh[0].push_back(1);        rowIndex += 1;        if(rowIndex == 1)            return finsh[0];        else{              for(int i = 1; i < rowIndex; i++){                    if(i == finsh.size())                    {                        vector<int> add;                        finsh.push_back(add);                    }                     finsh[i].push_back(1);                    for(int j = 1; j <= i; j++){                        if(finsh[i].size() == i)                            finsh[i].push_back(1);                        else{                            int x = finsh[i-1][j-1];                            int y = finsh[i-1][j];                            int elem = x + y;                            finsh[i].push_back(elem);                        }                    }               }               return finsh[rowIndex-1];         }    }};
0 0
原创粉丝点击