【Leetcode】Pascal's Triangle

Given numRows, generate the first numRows of Pascal's triangle.

For example, given numRows = 5,
Return

[
     [1],
    [1,1],
   [1,2,1],
  [1,3,3,1],
 [1,4,6,4,1]
]

分析:本行的中间第i个元素等于上一行的第(i-1) 与第 i个元素之和;

class Solution {
public:
    vector<vector<int> > generate(int numRows) {
        vector<vector<int>> result;
        
        if(numRows <= 0)
            return result;
            
        vector<int> temp;
        temp.push_back(1);
        result.push_back(temp);
        
        if(numRows >= 2)
        {
            temp.push_back(1);
            result.push_back(temp);
        }
        
        for(int i = 2;  i < numRows; i++)
        {
            const vector<int> &former_vec = result[i - 1];
            vector<int> temp_vec;
            temp_vec.push_back(1);
            for(int j = 1; j < i; j++)
                temp_vec.push_back(former_vec[j - 1] + former_vec[j]);
            temp_vec.push_back(1);
            
            result.push_back(temp_vec);
        }
        
        return result;
            
    }
};





你可能感兴趣的:(【Leetcode】Pascal's Triangle)