Pascal's Triangle II

来源:互联网 发布:和合期货软件下载 编辑:程序博客网 时间:2024/05/20 06:40

题目:Given an index k, return the kth row of the Pascal's triangle.

For example, given k = 3,
Return [1,3,3,1].

思路:递推

思路很明确,一层一层递推,并且只需要设立一个数组,本题不难。只需要注意一个解题公式即可

代码:

class Solution1 {public://for more information,please email:j.z.feng@foxmail.com    vector<int> getRow(int rowIndex) {        vector<int> result(1,1);        if(rowIndex==0){            return result;        }                for(int i=1;i<=rowIndex;i++){            vector<int>temp=result;            for(int j=1;j<=i-1;j++){                result[j]=temp[j]+temp[j-1];            }            result.push_back(1);            temp.clear();        }        return result;    }};

class Solution2 {//此版本更加简洁public:<pre name="code" class="cpp">//for more information,please email:j.z.feng@foxmail.com
vector<int> getRow(int rowIndex) { vector<int> result(rowIndex+1,1); if(rowIndex<=1){ return result; } for(int i=2;i<=rowIndex;i++){ for(int j=i-1;j>=1;j--){ result[j]=result[j]+result[j-1]; } } return result; }};



0 0
原创粉丝点击