Pascal's Triangle

来源:互联网 发布:java数组去重排序 编辑:程序博客网 时间:2024/05/20 02:53
class Solution {public:    vector<vector<int> > generate(int numRows) {        vector<vector<int> > res;        if (numRows==0) return res;        vector<int> cur(1,1);        res.push_back(cur);        if (numRows==1) return res;        for (int n=1; n<numRows; n++) {            vector<int> cur(1,1);            for (int i=1; i<n; i++) {                cur.push_back(res[n-1][i-1]+res[n-1][i]);            }            cur.push_back(1);            res.push_back(cur);        }        return res;    }};


II:

class Solution {public:    vector<int> getRow(int rowIndex) {        vector<int> res;        res.push_back(1);        if (rowIndex==0) return res;        vector<int> t(rowIndex+1,1);        vector<vector<int> > r(2,t);        int now=1, pre=0;        for (int n=1; n<rowIndex+1; n++) {            for (int i=1; i<n; i++) {                r[now][i]=r[pre][i-1]+r[pre][i];            }            if (n!=rowIndex) {                if (now==1) {now=0; pre=1;}                else {now=1; pre=0;}            }        }        return r[now];    }};

Better Solution:

class Solution {public:    vector<int> getRow(int rowIndex) {        vector<int> res;        for (int n=0; n<rowIndex+1; n++) {            for (int i=n-1; i>0; i--) {                res[i]=res[i-1]+res[i];            }            res.push_back(1);        }        return res;    }};



0 0