(LeetCode每日一刷19) 杨辉三角

题目描述:

在杨辉三角中,每个数是它左上方和右上方的数的和。

示例:

输入: 5
输出:
[
     [1],
    [1,1],
   [1,2,1],
  [1,3,3,1],
 [1,4,6,4,1]
]

我提交的代码:

class Solution {
public:
    vector<vector<int>> generate(int numRows) {
        vector<int> preVec;
        vector<vector<int>> result;
        int i;
        for (i = 1; i <= numRows; ++i){
            vector<int> tempVec;
            if(1 == i){
                tempVec.push_back(1);
            }
            else{
                int preSize = preVec.size();
                tempVec.push_back(1);
                for (int j = 0; j < preSize - 1; ++j){
                    int addVal = preVec[j] + preVec[j+1];
                    tempVec.push_back(addVal);
                }
                tempVec.push_back(1);   
            }
            result.push_back(tempVec);
            preVec = tempVec;       
        }
        return result;
    }
};

猜你喜欢

转载自blog.csdn.net/songsong2017/article/details/84618054